使用where子句在SQL Server中进行透视

时间:2017-03-19 14:42:01

标签: sql sql-server sql-server-2008 pivot

我需要在SQL中使用Pivot获取按列转换的行,但不能通过我的数据透视查询执行此操作。

    create table TestTable
    (
      id int,
      colVal int
    )

insert into TestTable values(1,1)
insert into TestTable values(1,2)
insert into TestTable values(1,4)
insert into TestTable values(2,1)
insert into TestTable values(2,2)
insert into TestTable values(2,6)

我试图根据下面的查询where子句获取列中colVal的值。

select * from
(
    Select ID,colVal
    from TestTable
    where ID=1
) as PV
pivot
(max(id) for colVal in([1], [2], [3])) piv

对于每个ID,只能有3个colValues,因此我在数据透视中指定了[1],[2],[3]。

I am looking for output like
ID  c1 c2 c3
1   1  2  4

任何人都可以帮助我。

1 个答案:

答案 0 :(得分:5)

只需使用Row_Number()创建列序列

select id,[1] as c1,[2] as c2,[3] as c3 from
(
    Select ID
          ,col    = row_number() over (Partition By ID Order by colVal)
          ,colVal
    from TestTable
    where ID=1
) as PV
pivot
(max(colVal) for col in([1], [2], [3])) piv

返回

ID  c1  c2  c3
1   1   2   4
  

编辑 - 动态版

Declare @SQL varchar(max) = Stuff((Select Distinct ',' + QuoteName(concat('C',row_number() over (Partition By ID Order by colVal))) 
                                    From  TestTable  
                                    Order By 1 
                                    For XML Path('')
                                  ),1,1,'') 
Select  @SQL = '
Select [id],' + @SQL + '
From (
        Select ID
              ,col    = concat(''C'',row_number() over (Partition By ID Order by colVal))
              ,colVal
        from TestTable
        where ID=1
     ) A
 Pivot (max(colVal) For [col] in (' + @SQL + ') ) p'
Exec(@SQL);
  

2008年编辑

Declare @SQL varchar(max) = Stuff((Select Distinct ',' + QuoteName('C'+cast(row_number() over (Partition By ID Order by colVal) as varchar(10))) 
                                    From  TestTable  
                                    Order By 1 
                                    For XML Path('')
                                  ),1,1,'') 
Select  @SQL = '
Select [id],' + @SQL + '
From (
        Select ID
              ,col    = ''C''+cast(row_number() over (Partition By ID Order by colVal) as varchar(10))
              ,colVal
        from TestTable
        where ID=1
     ) A
 Pivot (max(colVal) For [col] in (' + @SQL + ') ) p'
Exec(@SQL);