添加总列PIVOT TABLE

时间:2016-08-08 18:53:24

标签: sql-server sql-server-2008 pivot-table sql-server-2014

以下是我的代码人员,我希望能够返回2016,2015,2014,2013的总列,但是当我这样做时

Sum([2016]+[2015]+[2014]+[2013])像这样的收入它返回NULLS。

或者这个 Sum(2016+2015+2014+2013)因为像这样的收入返回的数字不同于你去2013年2015年和2016年计算并添加数字的数字 这些数字不会累计在总列中。

 SELECT        AirCarrierName, 
        SUM([2016]) AS [2016], 
        SUM([2015]) AS [2015], 
        SUM([2014]) AS [2014], 
        SUM([2013]) AS [2013]

        FROM            Sum_Orders 


        PIVOT
        (
         SUM(Sum_Orders.Sum_SellPrice)
                FOR Sum_Orders.OrderperiodYear IN ([2016],[2015],[2014],[2013])
            )AS pvt 

            WHERE OrderStatus IN ('INVOICED','OPEN') AND AirCarrierName 
    NOT LIKE 'NULL' 
    and AirCarrierName = 'CATHAY PACIFIC AIRWAYS LTD.'

            GROUP BY AirCarrierName


            Order by [2016] desc

此代码返回以下内容 enter image description here

当我添加用于创建总列的行时,这就是我得到的, 而不是总列中2013年至2016年的总和

Sum([2016]+[2015]+[2014]+[2013]) as total

enter image description here

这是包含总列的查询,返回Nulls

SELECT        AirCarrierName, 
SUM(Sum_BuyPrice) AS Buy_price, 
SUM(Sum_SellerMargin) AS Margin, sum(Sum_GrossWeightkg/1000)as Kilos_total,
                    SUM([2016]) AS [2016], 
SUM([2015]) AS [2015], SUM([2014]) AS [2014], SUM([2013]) 
                         AS [2013],

                    SUM([2016]+[2015]+[2014]+[2013])as [total]

FROM            Sum_Orders 


PIVOT
(
 SUM(Sum_Orders.Sum_SellPrice)
        FOR Sum_Orders.OrderperiodYear IN ([2016],[2015],[2014],[2013])
    )AS pvt 

    WHERE OrderStatus IN ('INVOICED','OPEN') AND AirCarrierName NOT LIKE 'NULL'

    GROUP BY AirCarrierName

0 个答案:

没有答案