如何从此SQL查询编写PIVOT查询

时间:2014-11-26 09:35:22

标签: sql sql-server pivot

我在SQL Server 2014上运行了以下SQL Query(感谢Thorsten!)。目前,我将输出导出到Excel 2013并从那里运行我的数据透视表。我知道有一种方法可以编写SQL PIVOT查询,以便输出与Excel中的输出完全相同。

我的SQL查询如下:

SELECT 
  b.PropertyCode,
  x.[ReservationStayID],
  x.[Nights Spent],
  x.[MTH],
  x.[Rate],
  x.CreatedOn,
  x.[DateOfArrival],
  x.[DateOfDeparture]

 FROM GuestNameInfo a
 JOIN GuestStaySummary b ON a.ReservationStayID = b.ReservationStayID
 LEFT JOIN ReservationStay c ON c.ReservationStayID = b.ReservationStayID
 LEFT JOIN
 (
   SELECT 
     ReservationStayID,
     datename(m,StayDate) + ' ' + cast(datepart(yyyy,StayDate) as varchar) as [MTH],
     count(*) AS [Nights Spent],
     avg(RateAmount) as [Rate],
     min(CreatedOn) as CreatedOn,
     min(StayDate) as [DateOfArrival],
     max(StayDate) as [DateOfDeparture]
   FROM ReservationStayDate
  GROUP BY ReservationStayID, datename(m,StayDate) + ' ' + cast(datepart(yyyy,StayDate) as varchar)
 ) x ON x.ReservationStayID = b.ReservationStayID

 WHERE a.PrimaryGuest = '+'

 AND NOT a.DepartureDate < '2014-11-01'

 AND NOT (b.ReservationStatus = 'CANCELED' OR b.ReservationStatus = 'NOSHOW')

 AND NOT b.MarketSegmentCode = 'COMP'

我需要SQL PIVOT代码给我以下输出:

PropertyCode     October 2014   November 2014  ....... April 2015

  AB                256              154        ......  247
  SD                143              315        ......  189

上述输出中的值是Nights Spent的总和。

当前SQL查询的输出如下:

PropertyCode     ReservationStayId    Nights Spent   MTH            Rate ......Date of Departure
AB                  5123                  12         November 2014   125.30 ....  2014-11-25

1 个答案:

答案 0 :(得分:0)

首先,将yout查询结果放入临时表:

SELECT 
  b.PropertyCode,
  x.[ReservationStayID],
  x.[Nights Spent],
  x.[MTH],
  x.[Rate],
  x.CreatedOn,
  x.[DateOfArrival],
  x.[DateOfDeparture]

 INTO #tmp /*HERE*/

 FROM GuestNameInfo a
 JOIN GuestStaySummary b ON a.ReservationStayID = b.ReservationStayID
 LEFT JOIN ReservationStay c ON c.ReservationStayID = b.ReservationStayID
 LEFT JOIN
 (
   SELECT 
     ReservationStayID,
     datename(m,StayDate) + ' ' + cast(datepart(yyyy,StayDate) as varchar) as [MTH],
     count(*) AS [Nights Spent],
     avg(RateAmount) as [Rate],
     min(CreatedOn) as CreatedOn,
     min(StayDate) as [DateOfArrival],
     max(StayDate) as [DateOfDeparture]
   FROM ReservationStayDate
  GROUP BY ReservationStayID, datename(m,StayDate) + ' ' + cast(datepart(yyyy,StayDate) as varchar)
 ) x ON x.ReservationStayID = b.ReservationStayID

 WHERE a.PrimaryGuest = '+'

 AND NOT a.DepartureDate < '2014-11-01'

 AND NOT (b.ReservationStatus = 'CANCELED' OR b.ReservationStatus = 'NOSHOW')

 AND NOT b.MarketSegmentCode = 'COMP'

然后只选择有关枢轴的列(使用##进入全局临时):

SELECT PropertyCode,[Nights Spent] as Nights,MTH
INTO ##temporary_for_pivot
FROM #tmp

然后选择临时列名的值(这里可以为列命令...):

IF OBJECT_ID('tempdb..#temp_for_columnames') IS NOT NULL DROP TABLE #temp_for_columnames
SELECT DISTINCT MTH
INTO #temp_for_columnames
FROM ##temporary_for_pivot

然后创建动态数据透视表脚本(因为你不知道列数)并运行它:

DECLARE @COLUMNS VARCHAR(MAX) 
SET @COLUMNS = 
STUFF(CAST((SELECT ',' + QUOTENAME(MTH) FROM #temp_for_columnames FOR XML PATH(''), TYPE) AS VARCHAR(MAX)),1,1,'')

DECLARE @cmd VARCHAR(MAX) 

SET @cmd = 'SELECT PropertyCode, '+@COLUMNS+'
            FROM ##temporary_for_pivot
            PIVOT ( SUM(Nights) FOR MTH IN ('+@COLUMNS+')) x'

EXEC(@cmd)

完成:)