【问题标题】:SQL Server Pivot Table HelpSQL Server 数据透视表帮助
【发布时间】:2010-10-07 11:22:39
【问题描述】:

我正在尝试转下面的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 临时表路由来将数据转换为这种格式。

谢谢

【问题讨论】:

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


    【解决方案1】:

    这是一种方法。它实际上需要和 unpivot 和一个 pivot 操作。 unpivot 将 Meetings 和 Covers 合并到一个列中,并将 TypeName 值更改为所需的列名。

    pivot 使用 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
    

    【讨论】:

    • 正是我所需要的谢谢。真的希望我能理解整个 Pivot 的事情,但是我真的很难掌握它的一些东西