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

标签 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 个 colValue,因此我在数据透视表中指定了 [1]、[2]、[3]。

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

谁能帮帮我。

最佳答案

只需使用 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

EDIT - Dynamic Version

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);

EDIT for 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);

关于sql - 使用 where 子句在 SQL Server 中进行透视,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42887871/

相关文章:

sql-server - SQL Server 日期格式取决于用户吗?

sql - 清除 SQL 表

SQL 服务器 : get all parent child URL's from a single table

sql - 对相关表的约束

java - #1411 - 不正确的日期时间值 : '11:21:21' for function str_to_date

sql - 非聚集索引在不同列类型上的性能

sql - 如果地址空间是连续的,对 IDENTITY 列的查找是否会更快?

sql - 使用从同一表计算的值更新表的最佳方法

sql - 如何使用 JSON_VALUE 对 JSON 数据设置多个过滤器?

mysql - 如何使用DBNull.Value检查表列是否为空;如果不为空则返回默认值