透视SQL表(行到列)

时间:2015-06-11 08:33:01

标签: sql sql-server pivot-table

我目前正在将数据返回到SQL存储过程中的表中。我试图将行转换为列,将列转换为行,但我正在努力这样做,因为我遵循的许多教程都表明它们的表格不同。

这是我的存储过程底部的选择:

select 

(CASE WHEN [Fitter] IS NULL THEN (Select Distinct substring([First Name],1,1)+' '+[Second Name] from Fitters where [Fitter Id]=FitterId) ELSE Fitter END) AS Fitter,
sum([Install Sell]) as [Install Sell],
sum([Install Cost]) as [Install Cost],
sum([Install Cost Amt]) as Gross,
(select cast(CAST((TaxStatus/100 * sum([Install Cost Amt])) as decimal(18,5)) as float)) as CIS,
(select cast(CAST((VatStatus/100 * sum([Install Cost Amt])) as decimal(18,5)) as float)) as VAT,
sum([Install Cost Amt]) - (select cast(CAST((TaxStatus/100 * sum([Install Cost Amt])) as decimal(18,5)) as float)) + (select cast(CAST((VatStatus/100 * sum([Install Cost Amt])) as decimal(18,5)) as float)) as FittersPay,
sum([Install Cost Amt]) + (select cast(CAST((VatStatus/100 * sum([Install Cost Amt])) as decimal(18,5)) as float)) as Datafile

from @TempTable
group by FitterId, Fitter, TaxStatus, VatStatus

这是它返回的数据: enter image description here

我希望列可以作为行进行旋转,而行可以作为列进行旋转...

我在网上搜索过,我正在努力解决这个问题,我想知道我是否能得到一些帮助。

感谢任何帮助。

1 个答案:

答案 0 :(得分:2)

这是通过首先取消隐藏然后转动来完成的。这是一个示例,您可以调整您的数据:

DECLARE @t TABLE(col0 VARCHAR(20), col1 MONEY, col2 MONEY, col3 MONEY)

INSERT INTO @t VALUES
('aaaaaa', 1, 1.2, 0),
('bbbbbb', 2, 2.2, 0),
('cccccc', 3, 3.3, 100),
('dddddd', 4, 4.4, 0)

SELECT * FROM @t 

SELECT * FROM @t
UNPIVOT (a FOR b IN([col1],[col2],[col3])) up
PIVOT (MAX(a) FOR col0 IN([aaaaaa],[bbbbbb],[cccccc],[dddddd])) p

输出1:

col0    col1    col2    col3
aaaaaa  1.00    1.20    0.00
bbbbbb  2.00    2.20    0.00
cccccc  3.00    3.30    100.00
dddddd  4.00    4.40    0.00

输出2:

b       aaaaaa  bbbbbb  cccccc  dddddd
col1    1.00    2.00    3.00    4.00
col2    1.20    2.20    3.30    4.40
col3    0.00    0.00    100.00  0.00

这取决于您的数据类型,但您可能需要动态执行此操作。网站上有很多例子。只需搜索dynamic pivoting

修改

这样的事情:

select * from (
select 

(CASE WHEN [Fitter] IS NULL THEN (Select Distinct substring([First Name],1,1)+' '+[Second Name] from Fitters where [Fitter Id]=FitterId) ELSE Fitter END) AS Fitter,
sum([Install Sell]) as [Install Sell],
sum([Install Cost]) as [Install Cost],
sum([Install Cost Amt]) as Gross,
(select cast(CAST((TaxStatus/100 * sum([Install Cost Amt])) as decimal(18,5)) as float)) as CIS,
(select cast(CAST((VatStatus/100 * sum([Install Cost Amt])) as decimal(18,5)) as float)) as VAT,
sum([Install Cost Amt]) - (select cast(CAST((TaxStatus/100 * sum([Install Cost Amt])) as decimal(18,5)) as float)) + (select cast(CAST((VatStatus/100 * sum([Install Cost Amt])) as decimal(18,5)) as float)) as FittersPay,
sum([Install Cost Amt]) + (select cast(CAST((VatStatus/100 * sum([Install Cost Amt])) as decimal(18,5)) as float)) as Datafile

from @TempTable
group by FitterId, Fitter, TaxStatus, VatStatus) t

UNPIVOT (a FOR b IN([Install Sell],[Install Cost],[Gross]/*,...*/)) up
PIVOT (MAX(a) FOR Fitter IN([D Page],[J Hopley]/*,...*/)) p