SQL Query以将百分比的输出表示为百分比

时间:2014-12-24 21:14:15

标签: sql sql-server pivot

我在SQL Server 2014中运行了以下SQL查询,它运行正常。现在我需要修改查询,以便将输出表示为百分比(更多详细信息请参见下文)。

SELECT *
FROM   (SELECT [PropertyCode],
           [MTH],
           [ROOM NIGHTS]
    FROM   HOLDINGS) a
   PIVOT (Sum([ROOM NIGHTS])
         FOR [MTH] IN ([NOVEMBER 2014],
                       [DECEMBER 2014],
                       [JANUARY 2015])) AS PVTTABLE

以上查询中的HOLDINGS是一个View Table。

上述查询的输出如下所示:

PropertyCode   NOVEMBER 2014    DECEMBER 2014  JANUARY 2015
HOTEL A          1,200              560            700
HOTEL B          900                430            500
HOTEL C          800                650            200

HOTEL A酒店拥有65间客房,酒店B 120间客房和C酒店拥有50间客房,这些信息位于名为CAPACITY的桌子上,其中包含“PropertyCode”和“Rooms”栏目(列出如上所述的客房数量)。 / p>

我需要修改我的数据透视查询,以便输出如下所示:

PropertyCode   NOVEMBER 2014    DECEMBER 2014  JANUARY 2015
HOTEL A          61%               28%             35%
HOTEL B          25%               11%             13%
HOTEL C          53%               42%             13%

百分比计算如下: ROOM NIGHTS /(特定酒店房间数*每月天数)* 100

我想我需要LEFT JOIN来匹配来自HOLDINGS视图表和CAPACITY表的PropertyCode,我还需要修改原始查询中的“PIVOT(Sum([ROOM NIGHTS])”部分,以便它计算输出为%,但我不知道如何编写语法。

1 个答案:

答案 0 :(得分:1)

这些方面的内容应该有效:

SELECT  [PropertyCode],[MTH], 
[NOVEMBER 2014]/(SELECT rooms FROM capacity c WHERE c.propertycode=pvttable.propertycode)*30*100. as nov2014, 
[DECEMBER 2014]/(SELECT rooms FROM capacity c WHERE c.propertycode=pvttable.propertycode)*31*100. as dec2014, 
[JANUARY 2015]/(SELECT rooms FROM capacity c WHERE c.propertycode=pvttable.propertycode)*31*100.  as jan2015
FROM   (SELECT [PropertyCode],
           [MTH],
           [ROOM NIGHTS]
    FROM   HOLDINGS) a
   PIVOT (Sum([ROOM NIGHTS])
         FOR [MTH] IN ([NOVEMBER 2014],
                       [DECEMBER 2014],
                       [JANUARY 2015])) AS PVTTABLE

或使用JOIN代替相关查询:

SELECT  [PropertyCode],[MTH], 
[NOVEMBER 2014]/rooms * 30 * 100. AS Nov2014, 
[DECEMBER 2014]/rooms * 31 * 100. AS Dec2014, 
[JANUARY 2015]/rooms  * 31 * 100. AS Jan2015
FROM   (SELECT [PropertyCode],
           [MTH],
           [ROOM NIGHTS]
    FROM   HOLDINGS) a
   PIVOT (Sum([ROOM NIGHTS])
         FOR [MTH] IN ([NOVEMBER 2014],
                       [DECEMBER 2014],
                       [JANUARY 2015])) AS PVTTABLE
JOIN capacity c ON c.propertycode=pvttable.propertycode