SQL Server数据透视表帮助

时间:2010-10-07 11:22:39

标签: sql-server sql-server-2005 pivot

我正在尝试关闭以下ResultSet

Meetings Covers   Date         TypeName
1         3       2010-10-14   Breakfast
1         1       2010-10-14   LunchCooked
2         4       2010-10-15   Breakfast
1         3       2010-10-18   Breakfast
1         3       2010-10-19   Breakfast
1         1       2010-10-19   LunchSandwich
1         3       2010-10-20   Breakfast
1         3       2010-10-21   Breakfast
1         3       2010-10-22   Breakfast

转换为具有以下字段的格式

Date
BreakfastMeetings
BreakfastCovers
LunchSandwichMeetings
LunchSandwichCovers
LunchCookedMeetings
LunchCookedCovers

我是否认为可以使用数据透视表进行此操作?任何指针都会很棒,否则我最终会采取某种hacky临时表路径来获取这种格式的数据。

由于

1 个答案:

答案 0 :(得分:1)

这是一种方法。它实际上需要和univot和一个枢轴操作。 unpivot将会议和封面组合成一个列,并将TypeName值更改为所需的列名。

数据透视表使用unpivot的结果提供最终格式。

SELECT TheDate, BreakfastMeetings, BreakfastCovers, LunchSandwichMeetings,
    LunchSandwichCovers, LunchCookedMeetings, LunchCookedCovers
FROM (
    -- unpivot to put counts in single column and create new type names
    SELECT TheDate, TypeName + MeetingCover AS TypeName, RowCounts
    FROM (SELECT TheDate, TypeName, Meetings, Covers
        FROM MyTable
        ) AS p
        UNPIVOT (RowCounts FOR MeetingCover IN (Meetings, Covers)
        ) AS UnpivotTable
    ) AS Source
    -- pivot the unpivoted data to create new columns
    PIVOT ( MAX(RowCounts) FOR TypeName IN (BreakfastMeetings, BreakfastCovers,
                                            LunchSandwichMeetings,
                                            LunchSandwichCovers,
                                            LunchCookedMeetings,
                                            LunchCookedCovers)
) AS PivotTable
ORDER BY TheDate