如何为交叉表报告编写mysql?

时间:2013-04-10 11:25:23

标签: php mysql sql pivot

我有3个表'media','zone'和'mediaplaycount'想要编写查询来获取数据以交叉表格式表示它。

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

1 个答案:

答案 0 :(得分: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;