-5

我有一个表有这样的记录:

Particluar       | Amount
Excise Duty 12 % | 2775.00
Edu CESS 2%      | 56.00
HR Edu CESS 1%   | 28.00
Sale CST 2%      | 520.00

如何从选择查询中获取以下内容?

Excise Duty 12 % | Edu CESS 2% | HR Edu CESS 1% | Sale CST 2%
2775.00          | 56.00       | 28.00          | 520.00
4

2 回答 2

6

有几种方法可以将数据从行透视到列。

您可以将聚合函数与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)
于 2013-04-30T11:53:56.490 回答
1

试试这个——

SELECT pt.*
FROM dbo.table1 o
PIVOT
(
    COUNT(o.Amount)
    FOR o.Particluar IN (
          [Excise Duty 12 %]  
        , [Edu CESS 2%] 
        , [HR Edu CESS 1%]
        , [Sale CST 2%]
    )
) pt
于 2013-04-30T10:41:32.983 回答