2014-10-29 81 views
0

我不知道與MySQL。我有幾個小時試圖編寫一些與「concat組」有關的答案,以便將行數據透視到列。樞紐MySQL不工作

我的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

試試這個(情況下,如果方法)

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 
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

嘗試這樣

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