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

Abh*_*sia 2 sql sql-server pivot sql-server-2008

我需要在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)
Run Code Online (Sandbox Code Playgroud)

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

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

对于每个ID,只能有3个colValues,因此我在pivot中指定了[1],[2],[3].

I am looking for output like
ID  c1 c2 c3
1   1  2  4
Run Code Online (Sandbox Code Playgroud)

有人可以帮我从这里出去吗.

Joh*_*tti 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
Run Code Online (Sandbox Code Playgroud)

返回

ID  c1  c2  c3
1   1   2   4
Run Code Online (Sandbox Code Playgroud)

编辑 - 动态版

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);
Run Code Online (Sandbox Code Playgroud)

编辑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);
Run Code Online (Sandbox Code Playgroud)