我正在使用Mysql,我想要计算不同的值,然后将不同的值作为列名。
我有一张桌子这样的学生
ID Names Age
1 Tim 12
2 James 14
3 White 13
4 John 13
5 Annie 11
6 Judy 13
我想知道每个年龄段有多少人。我的预期结果是:
11 12 13 14
1 1 3 1
我尝试了查询:"Select count(age), age from Students group by age;"
它给出了:
count(age) age
1 11
1 12
3 13
1 14
如何将“转置”带到桌子上?
答案 0 :(得分:1)
如果您使用SELECT
SUM(CASE WHEN (age='11') THEN 1 ELSE 0 END) AS 11,
SUM(CASE WHEN (age='12') THEN 1 ELSE 0 END) AS 12,
SUM(CASE WHEN (age='13') THEN 1 ELSE 0 END) AS 13,
SUM(CASE WHEN (age='14') THEN 1 ELSE 0 END) AS 14
FROM
Students
,则需要提前知道年龄:
toDouble()