PIVOT
一、一列
SELECT MM,[2016-06],[2016-07],[2016-08],[2016-09],[2016-10],[2016-11],[2016-12] FROM (SELECT 'TEU/CBM' AS MM,cbm,khrq FROM #tmp_result) AS ss PIVOT ( sum(cbm) FOR khrq IN ([2016-06],[2016-07],[2016-08],[2016-09],[2016-10],[2016-11],[2016-12]) ) AS pp
-- ****
-- 等同
-- ****
SELECT *
FROM (SELECT 'TEU/CBM' AS MM,cbm,khrq FROM #tmp_result) AS ss PIVOT ( sum(cbm) FOR khrq IN ([2016-06],[2016-07],[2016-08],[2016-09],[2016-10],[2016-11],[2016-12]) ) AS pp
二、多列(列固定)
思路:CMB union all USD union RMB
SELECT * FROM (SELECT 'TEU/CBM' AS MM,cbm,khrq FROM #tmp_result) AS ss
PIVOT (
sum(cbm) FOR khrq IN ([2016-06],[2016-07],[2016-08],[2016-09],[2016-10],[2016-11],[2016-12])
) AS pp union all SELECT * FROM (SELECT '利润/USD' AS MM,cbm,khrq FROM #tmp_result) AS ss
PIVOT (
sum(usd) FOR khrq IN ([2016-06],[2016-07],[2016-08],[2016-09],[2016-10],[2016-11],[2016-12])
) AS pp union all SELECT * FROM (SELECT '利润/RMB' AS MM,cbm,khrq FROM #tmp_result) AS ss
PIVOT (
sum(rmb) FOR khrq IN ([2016-06],[2016-07],[2016-08],[2016-09],[2016-10],[2016-11],[2016-12])
) AS pp
二、多列(列 bu 不 固定)
create table #tmp (ID int,Item1 varchar(5),Number1 int,Number2 int) insert into #tmp select 1,'A',10,1 union all select 1,'B',5,3 union all select 1,'A',3,2 union all select 2,'A',5,3 union all select 2,'B',1,2 union all select 2,'B',2,2 -- select * FROM #tmp
select ID,Item1+'('+c+')' 'c',v into #tmp2 from (select ID,Item1,sum(Number1) 'Number1',sum(Number2) 'Number2' from #tmp group by ID,Item1) a unpivot(v for c in([Number1],[Number2])) u
-- select * FROM #tmp2
select ID,[A(Number1)],[A(Number2)],[B(Number1)],[B(Number2)]
from (SELECT * FROM #tmp2) b pivot(max(v) for c in([A(Number1)],[A(Number2)],[B(Number1)],[B(Number2)])) p