查询我需要这样

时间:2011-03-12 09:30:06

标签: sql sql-server-2005 tsql pivot

这是我的查询

SELECT CAL.CALENDAR_NAME,CAL.CALENDAR_ID,CALDAY.CALENDARDAY_DAYID 
FROM lms_calendar AS CAL
  LEFT JOIN LMS_CALENDARDAY AS CALDAY 
  ON CAL.CALENDAR_ID = CALDAY.CALENDARDAY_CALENDARID

我得到这样的结果

CALENDAR_NAME                                      CALENDAR_ID CALENDARDAY_DAYID
-------------------------------------------------- ----------- -----------------
Test                                               1           1
Test                                               1           2
Test                                               1           3
Test                                               1           4
Test                                               1           6

但我需要这样

calendar_name  calendar_dayid calendar_dayid calendar_dayid calendar_dayid calendar_dayid  
test              1                 2              3              4            

1 个答案:

答案 0 :(得分:2)

以下是使用PIVOT运算符

的查询
SELECT calendar_name, 
    [1] AS calendar_dayid, 
    [2] AS calendar_dayid, 
    [3] AS calendar_dayid, 
    [4] AS calendar_dayid, 
    [5] AS calendar_dayid
FROM (
    SELECT CAL.CALENDAR_NAME,CAL.CALENDAR_ID,CALDAY.CALENDARDAY_DAYID 
    FROM lms_calendar AS CAL
      LEFT JOIN LMS_CALENDARDAY AS CALDAY 
      ON CAL.CALENDAR_ID = CALDAY.CALENDARDAY_CALENDARID
    ) AS src
PIVOT (
    MAX(calendarday_dayid)
    FOR calendarday_dayid IN ([1], [2], [3], [4], [5])
    ) AS pvt