SQL查询以下面的情况转置数据

时间:2014-03-10 12:39:28

标签: sql sql-server pivot-table

我有以下SQL Server 2008 TABLE:

Heading     Limit   Package
X Charges   200     A
X Charges   300     B
X Charges   400     C
X Charges   500     D
Y Charges   550     A
Y Charges   450     B
Y Charges   350     C
Y Charges   250     D

现在我希望以下列表示获取数据:

Heading    Package_A   Package_B  Package_C  Package_D
X Charges  200         300        400        500
Y Charges  550         450        350        250

5 个答案:

答案 0 :(得分:2)

请尝试:

SELECT
  Heading, 
  A Package_A,
  B Package_B,
  C Package_C,
  D Package_D
FROM (
      SELECT * FROM YourTable
) up 
PIVOT (sum(Limit) FOR Package IN (A, B, C, D)) AS pvt

SQL Fiddle

答案 1 :(得分:0)

Fiddle here

SELECT 
    Heading, 
    [A] as Package_A, 
    [B] as Package_B, 
    [C] as Package_C, 
    [D] as Package_D
FROM
   TableX
PIVOT
(
  SUM(LIMIT)
  FOR Package IN ([A], [B], [C], [D])
) x;

动态案例(预先知道包的值)here

答案 2 :(得分:0)

请更新下表中的表名:

declare
    @cols nvarchar(max),
    @stmt nvarchar(max)

select @cols = isnull(@cols + ', ', '') + '[' + T.Package+ ']' 
     from (select distinct Package from TABLE1) as T

select @stmt = '
    select *
    from TABLE1 as T
        pivot 
        (
            max(T.VALUE)
            for T.Package in (' + @cols + ')
        ) as P'

exec sp_executesql  @stmt = @stmt

答案 3 :(得分:0)

Declare @t table( Heading varchar(50), Limit int,Package varchar(20)) 
insert into @t
select    'X Charges',   200,'A' union all
select  'X Charges',   300,'B' union all
select  'X Charges',   400,'C' union all
select  'X Charges',   500,'D' union all
select  'Y Charges',   550,'A' union all
select  'Y Charges',   450,'B' union all
select  'Y Charges',   350,'C' union all
select  'Y Charges',   250,'D'

select * from
(select * from @t)t4
pivot (min(limit) for Package in([A],[B],[C],[D]))pvt

答案 4 :(得分:0)

为了动态执行此操作:

Declare
@cols varchar(max)
select @cols =  stuff(
 (select distinct ',' + quotename(package)
from data
for xml path (''), type
).value('.', 'varchar(max)'), 1,1, '')  

declare 
@query varchar(max)

set @query = 'select distinct heading, ' + @cols + ' from
        (
            select   heading, Limit, Package
            from    data

        ) X
        pivot
        (
              MAX(Limit)
              for   Package in ('+@cols + ')
        ) p'

exec(@query)    

演示:http://sqlfiddle.com/#!3/8a42a/4