我有一个表格,可以为节目的剧集存储一行。请注意,并非每个剧集都存储。
showID | viewerID | episodeNumber | episodeDescription
____________________________________________________________________
15 | ID-123 | 1 | Scary
____________________________________________________________________
15 | ID-123 | 3 | Funny
我已经构建了一个数据透视查询来为剧集编号和描述创建列。剧集数量是已知数量。
showID | viewerID | episode1 | episode2 | episode3
__________________________________________________________________________
15 | ID-123 | Scary | funny |
我的问题是,如果没有一集的记录,如本例中第一个表中第2集缺少行所示,则查询不会创建一个"占位符"而是将episode3的数据放入episode2列。我甚至不知道我的需要是否可能 - 但我确实需要以某种方式确保当剧集编号没有数据(没有行)时剧集编号与正确的描述相关联,而且我确实需要为表2中的每一集显示一列(所以在上面的表2中,episode2的字段应为空白)。
我的查询如下:
SELECT viewerID, showID,
episodeDescription1, episodeDescription2, episodeDescription3
FROM
(
SELECT viewerID, showID, col+cast(seq as varchar(10)) as col, value
from
(
SELECT viewerID, showID, episodeNumber, episodeDescription,
row_number() over(partition by showID
order by episodeNumber) seq
FROM tbl_showEpisodes
) d
CROSS APPLY
(
SELECT 'episodeNumber', cast(episodeNumber as varchar(20))
UNION ALL
SELECT 'episodeDescription', episodeDescription
) c (col, value)
) src
pivot
(
MAX(value)
for col in (
episodeNumber1, episodeDescription1, episodeNumber2,
episodeDescription2, episodeNumber3, episodeDescription3)
) piv;
我希望这很清楚,并提前感谢任何帮助!使用SQL Server 2012.
答案 0 :(得分:2)
你可以这样做:
create table tbl_showEpisodes (showID int, viewerID varchar(30), episodeNumber int, episodeDescription varchar(30)); insert into tbl_showEpisodes values (15, 'ID-123', 1, 'Scary'), (15, 'ID-123', 3, 'Funny'); GO
SELECT showID, viewerID, [Episode 1], [Episode 2], [Episode 3] FROM (SELECT showID, viewerID, CONCAT('Episode ', episodeNumber) epNumber, episodeDescription FROM tbl_showEpisodes) src PIVOT (MAX(episodeDescription) FOR epNumber IN ([Episode 1],[Episode 2],[Episode 3])) pvt GO
showID | viewerID | Episode 1 | Episode 2 | Episode 3 -----: | :------- | :-------- | :-------- | :-------- 15 | ID-123 | Scary | null | Funny
dbfiddle here