我需要在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)
有人可以帮我从这里出去吗.