0

我有 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
4

1 回答 1

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;
于 2013-04-10T11:30:29.990 回答