MySQL 整个时间内按类别的成本

标签 mysql cost-management

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

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  |

使用“月份”属性下的记录作为列标题并在相应的“月份”列下分配成本记录的最佳方式是什么?

最佳答案

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”等。我认为它应该有效

关于MySQL 整个时间内按类别的成本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45971484/

相关文章:

php - 在特定查询上使用 sql LIMIT 1

php - 在mysql中使用WHERE子句显示运行余额但仅显示指定行

amazon-web-services - 当一个 lambda 调用另一个 lambda 时,数据传输成本

google-app-engine - 如何在 Google Developers Console 中设置成本限制

r - 最小化重新分配个人的成本

MYSQL合并2个表

php - MySQL修复两个表中的自动增量差距

azure - 从 VisualStudio 发布 Azure Functions 需要付费吗?

amazon-web-services - AWS Glue 定价与 AWS EMR

mysql - 对页面进行分组并从每组中获取 x 行数