有几种方法可以将数据从行透视到列。
您可以将聚合函数与CASE
表达式一起使用:
select
sum(case when Particluar='Excise Duty 12 %' then amount else 0 end) [Excise Duty 12 %],
sum(case when Particluar='Edu CESS 2%' then amount else 0 end) [Edu CESS 2%],
sum(case when Particluar='HR Edu CESS 1%' then amount else 0 end) [HR Edu CESS 1%],
sum(case when Particluar='Sale CST 2%' then amount else 0 end) Sale CST 2%]
from yourtable;
从 SQL Server 2005 开始,PIVOT函数可以将数据转换为列:
select *
from
(
select Particluar, Amount
from yourtable
) d
pivot
(
sum(amount)
for Particluar in ([Excise Duty 12 %], [Edu CESS 2%],
[HR Edu CESS 1%], [Sale CST 2%])
) piv;
如果您有未知数量的Particluar
值,那么您可以使用动态 SQL 来获取结果:
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT distinct ',' + QUOTENAME(Particluar)
from yourtable
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT ' + @cols + '
from
(
select Particluar, Amount
from yourtable
) x
pivot
(
sum(Amount)
for Particluar in (' + @cols + ')
) p '
execute(@query)