用于从 VIEW 表中提取数据的 SQL 透视查询

Posted

技术标签:

【中文标题】用于从 VIEW 表中提取数据的 SQL 透视查询【英文标题】:SQL Pivot Query to extract data from a VIEW Table 【发布时间】:2014-12-23 06:46:38 【问题描述】:

我使用的是 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 = '+'

我现在需要一个将针对上述视图表运行的数据透视查询。我已经编写了以下查询(如下所示),但我似乎遗漏了一些东西,因为我在运行代码时收到以下错误:“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

【问题讨论】:

【参考方案1】:

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 

【讨论】:

名称是 HOLDINGS。给我以下错误消息:“消息 207,级别 16,状态 1,第 6 行无效的列名 'ROOM NIGHTS'。” @user3115933 - 我在源查询中错过了[ROOM NIGHTS]。检查现在更新 谢谢。像魅力一样工作!

以上是关于用于从 VIEW 表中提取数据的 SQL 透视查询的主要内容,如果未能解决你的问题,请参考以下文章

SQL查询将2个表中的数据与数据透视组合

SQL 查询某字段数据所在的表

使用 Sql Developer Oracle 的动态数据透视查询

Java -SQL 查询从两个表中提取数据?

使用 VBA 从 SQL Server 查询 VIEW

需要从 SQL 表中透视数据