使用PIVOT到SQL服务器

时间:2011-01-09 09:12:39

标签: sql-server-2005

这是我想通过我的第一行选择做的抽象概念,我在这里展示,但我无法做到这一点。这里类别[0],类别[2] ..等代表类别列值...我知道这种语法不起作用,但我想做这样的事情。

----------------------------------------------------------
SELECT category[0], category[1], category[2], category[3], category[4], category[5]
FROM(
select Row_number() OVER(ORDER BY (SELECT 1)) AS 'Serial Number',  
EP.FirstName,Ep.LastName, Ep.SignUpID, [dbo].[GetBookingRoleName](ES.UserId,EP.BookingRole) as RoleName,  
(select top 1 convert(varchar(10),eventDate,103)from [3rdi_EventDates] where EventId=@ItemId) as EventDate,  
(CASE [dbo].[GetBookingRoleName](ES.UserId,EP.BookingRole)  
WHEN 'Employee - Marketing' THEN 'DC'  
WHEN 'Employee - Accounting' THEN 'DC'  
WHEN 'Coaches' THEN 'DC'  
WHEN 'Student Client' THEN 'ST'  
WHEN 'Guest Doctor' THEN 'GDC'  
---....more categories here, i just removed a few  
END) as Category  
from [3rdi_EventParticipants] as EP  
inner join [3rdi_EventSignup] as ES on EP.SignUpId = ES.SignUpId  
WHERE EP.EventId = @ItemId AND EP.PlaceStatus IN (0,3,4,8)  
and userid in(  
select distinct userid from userroles  
where roleid not in(19,20,21,22) and roleid not in(1,2, 25, 44))) Up
PIVOT(sum(First_Name+Last_Name)) FOR Category (category[0], category[1], category[2], category[3], category[4], category[5])
Group by (SignUpID)

这是我的内部select语句的结果,我想使用pivot重新排列。

 S.NO First_name      last_name   SignUpID  Rol_Name      EventDate category
    1   User1Name       User1Name       12  90 Day Client   11/01/2011  DC
    2   User1NameAtt1   User1NameAtt1   12  90 Day Client   11/01/2011  DC
    3   User4Name       User4Name       13  Student Client  11/01/2011  ST
    4   User4NameAtt1   User4NameAtt1   13  Student Client  11/01/2011  ST
    5   user1           user1           14  90 Day Client   11/01/2011  DC
    6   att1            att1            14  Employee-Acco   11/01/2011  AD
    7   User4NameAtt2   User4NameAtt2   15  Student Client  11/01/2011  ST
    8   easdsd          ertrt           15  90 Day Client   11/01/2011  DC
    9   User4NameAtt3   User4NameAtt3   15  Employee-Acco   11/01/2011  AD

我希望每个类别列值都应该成为列名,并且该列下面应该是名字和姓氏的串联,但是对于那些只有具有公共signUpID的行,所有first_name + last_name的表应该出现,如下所示。

0 个答案:

没有答案