1

抱歉,我对此缺乏了解,我在这里和其他地方进行了研究,但遇到了障碍(我的大脑)。我正在尝试在这样的表格中显示别墅的价格:

                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 ' Packages'但后来我被告知:

SELECT ACCOMMODATION_configurations.configurationName 无法绑定

提前感谢您的帮助!

4

1 回答 1

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
于 2013-05-10T15:16:05.470 回答