2013-04-10 37 views
0

我有3個表'媒體','區'和'mediaplaycount'想寫查詢來獲取數據以交叉表格格式表示。如何爲交叉表報告編寫mysql?

media 
medId  medname 
-----  ------- 
1   media1 
2   media2 
3   media3 
-   - 
-   - 
n   xyz 


zone 
znId  znName 
-----  ------ 
1   east 
2   west 
3   south 
4   north 
-   - 
-   - 
n   xyz 

mediaplaycount 
medId  znId  playdate 
------  -----  -------- 
1   2   1/12/2013 
1   1   1/12/2013 
3   3   1/12/2013 
4   1   1/12/2013 

我想要的是每個媒體和區域組合的mediaplacount。 橫向場將所有的區域和垂直將是媒體。 結果應該有對區域的媒體數量和看起來像

  east west  south  north ----- ------ n 
media1 1  1  0   0   0  0  0 
media2 0  0  0   0   0  0  0 
media3 0  0  1   0   0  0  0 
media4 1  0  0   0   0  0  0 
----- 
n 
+0

http://stackoverflow.com/questions/8920626/is-it-possible-to-use-crosstab-pivot-query-in-mysql – 2013-04-10 11:27:56

回答

0

爲更好的解決方案是創建Dynamic SQL,因爲也有znName

SET @sql = NULL; 
SELECT GROUP_CONCAT(DISTINCT 
     CONCAT('SUM(CASE WHEN c.znName = ''', 
       znName, 
       ''' THEN 1 ELSE 0 END) AS ', 
       CONCAT('`', znName, '`') 
       )) INTO @sql 
FROM `Zone`; 

SET @sql = CONCAT(' SELECT b.medName, ', @sql, ' 
        FROM media b 
          LEFT JOIN MediaPlayCount a 
           ON a.medID = b.medID 
          LEFT JOIN Zone c 
           ON a.znID = c.znID 
        GROUP BY b.MedName'); 

PREPARE stmt FROM @sql; 
EXECUTE stmt; 
DEALLOCATE PREPARE stmt;