我有查询,提供所有城市的月度加入员工数。 (在MySQL中)
SELECT SUBSTR(`JoiningDate`,4,3) as Month,
Location,
Count(*) as `EmployeeCount`
FROM `data`
WHERE Location IN ('NYC','SFO','LA')
GROUP BY Month,Location
输出采用这种格式 -
| Month|Location| Count|
-----------------------
| Jan | NYC | 100|
| Jan | SFO | 500|
| Jan | LA | 200|
| Feb | NYC | 100|
| Feb | SFO | 400|
| Feb | LA | 500|
我如何能够以一种格式转置数据,它会为每个城市生成每月相关计数的列?像下面的东西 -
| Month|NYC |SFO | LA |
-----------------------
| Jan |100 |500 |200 |
| Feb |100 |400 |500 |
| Mar |300 |300 |650 |
答案 0 :(得分:0)
您可以使用条件聚合:
select SUBSTR(`JoiningDate`, 4, 3) as Month,
sum(location = 'NYC') as `NYC`,
sum(location = 'SFO') as `SFO`,
sum(location = 'LA' ) as `LA`
from `data`
where Location in ('NYC', 'SFO', 'LA')
group by SUBSTR(`JoiningDate`, 4, 3)
它使用了以下事实:在MIME中,true的计算结果为1,而false的结果为0,您可以求和以查找所需的计数。