【问题标题】:MySQL Cost by Category throughout time整个时间按类别划分的 MySQL 成本
【发布时间】:2018-02-08 19:42:56
【问题描述】:

我有一个如下所示的表格:

Site | Category | Cost | Month |
A    | Hardware | 10   | 1     |
A    | Software | 30   | 1     |
B    | Software | 15   | 1     |
C    | Labor    | 5    | 2     |
...

我需要输出这个:

Site | Category |  1   |  2  | ...
A    | Hardware | 10   |  0  |
A    | Software | 30   |  0  |
B    | Software | 15   |  0  |
C    | Labor    |  0   |  5  |

将 Month 属性下的记录用作列标题并在其对应的 Month 列下分配 Cost 记录的最佳方法是什么?

【问题讨论】:

  • 您需要纯 SQL 响应吗?在纯 SQL 中获取可变数量的列是不可行的。您必须求助于另一种语言或使用创建临时表的存储过程。但是,如果您事先知道列数(在这种情况下正好是 12?),那么它是可行的
  • 是的,我需要一个纯 MySQL 响应。是的!我需要正好 12 列。你建议怎么做?
  • 认真考虑处理应用代码中数据显示的问题

标签: mysql cost-management


【解决方案1】:
SELECT Site, Category, 
   IF(Month=1,Cost,0) as M1,
   IF(Month=2,Cost,0) as M2,
   IF(Month=3,Cost,0) as M3,
   IF(Month=4,Cost,0) as M4,
   IF(Month=5,Cost,0) as M5,
   IF(Month=6,Cost,0) as M6,
   IF(Month=7,Cost,0) as M7,
   IF(Month=8,Cost,0) as M8,
   IF(Month=9,Cost,0) as M9,
   IF(Month=10,Cost,0) as M10,
   IF(Month=11,Cost,0) as M11,
   IF(Month=12,Cost,0) as M12
FROM tablename

会逐行给出。如果您希望每个 Category 有一行,可以添加 GROUP BY

SELECT Site, Category, 
   SUM(IF(Month=1,Cost,0)) as M1,
   SUM(IF(Month=2,Cost,0)) as M2,
   SUM(IF(Month=3,Cost,0)) as M3,
   SUM(IF(Month=4,Cost,0)) as M4,
   SUM(IF(Month=5,Cost,0)) as M5,
   SUM(IF(Month=6,Cost,0)) as M6,
   SUM(IF(Month=7,Cost,0)) as M7,
   SUM(IF(Month=8,Cost,0)) as M8,
   SUM(IF(Month=9,Cost,0)) as M9,
   SUM(IF(Month=10,Cost,0)) as M10,
   SUM(IF(Month=11,Cost,0)) as M11,
   SUM(IF(Month=12,Cost,0)) as M12
FROM tablename
GROUP BY Site, Category

将保留网站,但总结类别。

另外,如果您不喜欢该字段的 Mx 名称,您可以尝试使用 '1' .. '2' 等。我认为它应该可以工作

【讨论】:

  • 这太棒了!!非常感谢。关于这个问题的最后一个问题。我有 20 个站点和 4 个类别。我想汇总每个类别的所有费用,但也可以查看所有网站。有没有办法在保持网站不变的同时按类别分组?
  • 看例子,你可以玩 GROUP BY
  • 如何修复一个有几年的数据库?我尝试在最后使用 where 子句,但数字太大,我认为 sum() 函数每月执行数据,而不考虑最后的 where 子句。是否可以使用双 if 函数?类似于: sum(if(year(invoice_date)=2017, if(month(invoice_date)=1, Cost, 0), 0) as Jan ?我知道 excel 允许这样做,但我正在 MySQL Workbench 中尝试,它声称语法错误
  • 如果你有一个名为theYear的字段更改GROUP BY Site, Category, theYear
  • 告诉我你的确切脚本。但是你需要更多的列——不仅仅是M1,而是M1_2016 ...M12_2016、M1_2017..M12_2017等。另外,以防万一你不知道,它是AND和不是& (Month=1 AND Year=2016)
猜你喜欢
  • 1970-01-01
  • 2020-06-18
  • 1970-01-01
  • 2020-12-26
  • 2021-10-27
  • 1970-01-01
  • 2020-12-24
  • 2015-07-07
  • 2018-04-25
相关资源
最近更新 更多