MySQL 整个时间内按类别的成本
MySQL Cost by Category throughout time
我有一个 table 看起来像这样:
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 |
将月份属性下的记录用作列 headers 并将成本记录分配到相应月份列下的最佳方法是什么?
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' etc.I 认为它应该有效
我有一个 table 看起来像这样:
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 |
将月份属性下的记录用作列 headers 并将成本记录分配到相应月份列下的最佳方法是什么?
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' etc.I 认为它应该有效