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
答案 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