2010-10-07 125 views
1

我想用下面的字段SQL Server的数据透视表帮助

Date 
BreakfastMeetings 
BreakfastCovers 
LunchSandwichMeetings 
LunchSandwichCovers 
LunchCookedMeetings 
LunchCookedCovers 

难道我就在想这是可以使用数据透视表进行转以下的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 

进入的格式?任何指针都会很好,否则我将最终采取某种形式的临时表路由来将数据转换为这种格式。

谢谢

回答

1

这是一种方法。它实际上需要和unpivot和一个枢轴操作。 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 
+0

正是我需要的感谢。真的希望我可以让我的脑袋绕过整个Pivot的东西,但是有一些东西我很难抓住 – Gavin 2010-10-08 08:58:08