没有聚合的三个表的数据透视表

时间:2013-05-10 15:13:41

标签: sql sql-server pivot

对于我对此缺乏了解而道歉,我在这里和其他地方进行了研究,但已经碰到了一堵砖墙(我的大脑)。我试图在这样的表格中显示别墅的价格:

                SPRING     SUMMER     FALL      WINTER    MAX GUESTS
2 Rooms         $343       $288       $389      $467      2
3 Rooms         $456       $415       $536      $756      4
Whole Villa     $809       $789       $906      $1023     6

我认为PIVOT是我的困境的答案。我在MS Server 2008 R2上使用SQL Server 2008

季节,套餐和价格存储在3个表格中:

CONFIGURATIONS
--------------
configurationID
configurationName
maximumGuests

SEASONS
-------
seasonID
seasonName

CONFIGURATIONSEASONRATES
------------------------
seasonID
configurationID
price

根据我能够找到的例子,我得到了这个:

SELECT 'Packages', 'Summer', 'Winter', 'Christmas', 'Tropical'

FROM

(SELECT     ACCOMMODATION_configurations.configurationName, price
FROM         ACCOMMODATION_configurations INNER JOIN
                      ACCOMMODATION_configurationSeasonRates ON 
                      ACCOMMODATION_configurations.configurationID = ACCOMMODATION_configurationSeasonRates.configurationID INNER JOIN
                      ACCOMMODATION_seasons ON ACCOMMODATION_configurationSeasonRates.seasonID = ACCOMMODATION_seasons.seasonID) as somethingNice

PIVOT (sum(price) for ACCOMMODATION_configurations.configurationName IN (['Summer'],['Winter'],['Christmas'],['Tropical'])) as anyThing

但我收到错误

  

列前缀“ACCOMMODATION_configurations”与查询中使用的表名或别名不匹配

然后我尝试用 SELECT ACCOMMODATION_configurations.configurationName 替换 SELECT'包',但后来我被告知:

  

SELECT ACCOMMODATION_configurations.configurationName无法绑定

提前感谢您的帮助!

1 个答案:

答案 0 :(得分:3)

在PIVOT语法中,您需要删除ACCOMMODATION_configurations。同时删除FOR中值的单引号,您需要将Packages列添加到内部选择中。

所以代码将是:

-- this select will display the packages and the seasons
SELECT Packages, Summer, Winter, Christmas, Tropical
FROM
(
  -- add Packages to this select list
  SELECT Packages, ac.configurationName, price
  FROM ACCOMMODATION_configurations ac
  INNER JOIN ACCOMMODATION_configurationSeasonRates sr
    ON ac.configurationID = sr.configurationID 
  INNER JOIN ACCOMMODATION_seasons s
    ON sr.seasonID = s.seasonID
) as somethingNice
PIVOT 
(
  sum(price) 
  for configurationName IN ([Summer],[Winter],[Christmas],[Tropical])
) as anyThing

编辑,根据您的评论,您似乎可能需要:

-- this select will display the packages and the seasons
SELECT Packages, Summer, Winter, Christmas, Tropical
FROM
(
  SELECT ac.configurationName as Packages, price, seasonName
  FROM ACCOMMODATION_configurations ac
  INNER JOIN ACCOMMODATION_configurationSeasonRates sr
    ON ac.configurationID = sr.configurationID 
  INNER JOIN ACCOMMODATION_seasons s
    ON sr.seasonID = s.seasonID
) as somethingNice
PIVOT 
(
  sum(price) 
  for seasonName IN ([Summer],[Winter],[Christmas],[Tropical])
) as anyThing