我正在使用SQL Server 2014,我有以下查询(我已将其转换为VIEW表):
SELECT
b.PropertyCode,
c.PMSConfirmationNumber,
x.[ReservationStayID],
a.FirstName + ' ' + a.LastName AS 'Name',
b.ReservationStatus AS 'Status',
d.rsl_nationality AS 'Nationality',
d.rsl_rateplan AS 'Rate Plan Code',
d.rsl_roomtype AS 'Room Type',
d.rsl_mealplan AS 'Meal Plan',
b.GuestCount AS 'Total Guest',
x.[Nights Spent] AS 'Room Nights',
x.[MTH],
x.[Rate] AS 'Room Rate WITH VAT',
c.CurrencyCode,
h.ROE AS 'Rate of Exchange',
(x.[Nights Spent]*x.[Rate]*h.[ROE])/NULLIF(1.15,0) AS 'PkgRevenue, Excl. VAT',
((x.[Nights Spent]*x.[Rate]*h.[ROE])/1.15)/NULLIF((b.GuestCount*x.[Nights Spent]),0) AS 'GADR, Excl. VAT',
x.CreatedOn,
x.[DateOfArrival],
x.[DateOfDeparture],
e.TravelAgencyTypeCode AS 'Source of Business',
c.TAProfileID,
e.Name AS 'Tour Operator',
g.CountryGroup AS 'Market',
c.TAProfileID2,
e2.Name AS 'Booking Origin (1)',
g2.CountryGroup AS 'Booking Origin (2)',
FROM GuestNameInfo a
JOIN GuestStaySummary b ON a.ReservationStayID = b.ReservationStayID
LEFT JOIN ReservationStay c ON c.ReservationStayID = b.ReservationStayID
LEFT JOIN P5RESERVATIONLIST d ON d.rsl_code = b.ReservationStayID
LEFT JOIN TravelAgency e ON e.TravelAgencyID = c.TAProfileID
LEFT JOIN Market g ON e.CountryCode = g.CountryCode
LEFT JOIN TravelAgency e2 ON e2.TravelAgencyID = c.TAProfileID2
LEFT JOIN Market g2 ON e2.CountryCode = g2.CountryCode
LEFT JOIN Exrate h ON h.Ccode = c.CurrencyCode
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 d.rsl_primaryguest = '+'
我现在需要一个针对上面的View Table运行的Pivot查询。我写了下面的查询(如下所示)但似乎我遗漏了一些东西,因为我在运行代码时收到以下错误:" Msg 207,Level 16,State 1,Line 4 列名称无效' MTH'。"
SELECT [Tour Operator],[MTH]
FROM HOLDINGS
PIVOT (SUM([ROOM NIGHTS])
FOR [MTH] IN ([NOVEMBER 2014],[DECEMBER 2014],[JANUARY 2015]))
AS PVTTABLE
答案 0 :(得分:3)
这不是pivot
的正确语法,请确保您的视图名称为HOLDINGS
。
SELECT <non-pivoted COLUMN>,
[first pivoted column] AS <COLUMN name>,
[second pivoted column] AS <COLUMN name>,
...
[last pivoted column] AS <COLUMN name>
FROM
(<SELECT query that produces the data>)
AS <alias FOR the source query>
PIVOT
(
<aggregation FUNCTION>(<COLUMN being aggregated>)
FOR
[<column that contains the values that will become column headers>]
IN ( [first pivoted column], [second pivoted column],
... [last pivoted column])
) AS <alias FOR the PIVOT TABLE>
<optional ORDER BY clause>;
您的Pivot
查询应该是这样的。
SELECT *
FROM (SELECT [Tour Operator],
[MTH],
[ROOM NIGHTS]
FROM HOLDINGS) a
PIVOT (Sum([ROOM NIGHTS])
FOR [MTH] IN ([NOVEMBER 2014],
[DECEMBER 2014],
[JANUARY 2015])) AS PVTTABLE