我对mysql一无所知。我有几个小时试图编写一些与“concat group”相关的答案,用于将行数转换为列。
我的sql:
select month(device_datetime) as month,
device_platform as platform,
count(*) as total
from devices
group by month(device_datetime), platform
order by month desc
结果是我想要的,但我想制作平台列
month | platform | total
02 | windows | 10
02 | android | 08
03 | windows | 06
04 | Macintosh| 04
我想这样:
month | windows | android | macintosh
02 | 10 | 08 | 0
03 | 06 | 0 | 0
04 | 0 | 0 | 04
谢谢。我希望你能帮助我!
答案 0 :(得分:2)
您可以将条件和与IF运算符一起使用。请检查以下查询
select month(device_datetime) as month,
SUM(IF(device_platform= 'windows', 1, 0) ) as windows ,
SUM(IF(device_platform= 'android', 1, 0) ) as android,
SUM(IF(device_platform= 'Macintosh', 1, 0) ) as macintosh
from devices
group by month(device_datetime)
order by month desc
答案 1 :(得分:1)
试试这个
select month,
IF(device_platform= 'windows', total, 0) as windows ,
IF(device_platform= 'android', total, 0) as android,
IF(device_platform= 'Macintosh', total, 0) as macintosh
from devices
group by month
order by month
答案 2 :(得分:0)
试试这个(案例和方法)
CASE METHOD
SELECT month(device_datetime) AS month,
SUM(CASE WHEN device_platform = 'windows' THEN 1 ELSE 0 END) AS windows,
SUM(CASE WHEN device_platform = 'android' THEN 1 ELSE 0 END) AS android,
SUM(CASE WHEN device_platform = 'Macintosh' THEN 1 ELSE 0 END) AS Macintosh
FROM devices
GROUP BY month(device_datetime)
ORDER BY month desc
IF METHOD
SELECT month(device_datetime) as month,
SUM(IF(device_platform= 'windows', 1, 0) ) as windows ,
SUM(IF(device_platform= 'android', 1, 0) ) as android,
SUM(IF(device_platform= 'Macintosh', 1, 0) ) as macintosh
FROM devices
GROUP BY month(device_datetime)
ORDER BY month desc