创建以下查询,使用2个数据透视表作为收入和利润,但是要先按第1列利润再按第1列收入顺序

时间:2018-08-19 11:29:51

标签: sql-server

enter image description here

PIVOT查询:

Declare @cols nvarchar(max)
SELECT @cols= COALESCE (@cols+',['+shipmentmonth+' Profit]','['+shipmentmonth+' Profit]') from (select distinct  shipmentmonth from  MargaritaSales where ShipYearMonth >='201601'  ) P   
Declare @cols1 nvarchar(max)
SELECT @cols1= COALESCE (@cols1+',['+shipmentmonth+' Income]','['+shipmentmonth+' Income]') from (select distinct  shipmentmonth from  MargaritaSales where ShipYearMonth >='201601'  ) P1   
    --Declare @cols nvarchar(max)
    --SELECT @cols= COALESCE (@cols+',['+shipmentmonth+' Profit]'+'['+shipmentmonth+' Income]','['+shipmentmonth+' Profit]'+'['+shipmentmonth+' Income]') from (select distinct  shipmentmonth from  MargaritaSales where ShipYearMonth >='201601'  ) P 

--select @cols

 DECLARE @query NVARCHAR(MAX)
 SET @query =
'SELECT * 
 FROM ( SELECT  T.buyer,T.buyerid, T.shipmentmonth,T.shipmentmonth+ 
''Income'' as shipmentmonth1,
    (t.PROFIT +t.USDServiceIncome -t.USDServiceExpense) as Profit1,
    ( t.Income+t.OfficeIncome+t.USDServiceIncome) as Income1 
    FROM    MargaritaSales  T  where T.ShipYearMonth >=''201601'') up PIVOT 
    (sum(PROFIT1)  
    FOR shipmentmonth IN ('+ @cols +')) AS pvt1

    PIVOT (sum(Income1)   
            FOR shipmentmonth1 IN (+ @cols1 + ')) AS pvt2'

EXEC SP_EXECUTESQL @query 

1 个答案:

答案 0 :(得分:0)

在这种情况下,使用CASE STATEMENT比使用PIVOT

更容易

这是它的外观。您需要按照PIVOTing的操作转换为动态查询

SELECT  T.buyer, T.buyerid,
        SUM(CASE WHEN ShipYearMonth = 201601 THEN t.PROFIT + t.USDServiceIncome -t.USDServiceExpense END) as Profit1,
        SUM(CASE WHEN ShipYearMonth = 201601 THEN t.Income + t.OfficeIncome + t.USDServiceIncome) as Income1,
        SUM(CASE WHEN ShipYearMonth = 201602 THEN t.PROFIT + t.USDServiceIncome -t.USDServiceExpense END) as Profit2,
        SUM(CASE WHEN ShipYearMonth = 201602 THEN t.Income + t.OfficeIncome + t.USDServiceIncome) as Income2
FROM    MargaritaSales T  
WHERE   T.ShipYearMonth >= 201601
GROUP BY T.buyer, T.buyerid