枢轴查询:
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