我需要在 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/