【发布时间】:2020-09-12 04:14:28
【问题描述】:
【问题讨论】:
标签: sql sql-server tsql pivot window-functions
【问题讨论】:
标签: sql sql-server tsql pivot window-functions
您可以进行条件聚合。我怀疑你想要:
select
sbno,
max(case when test_name = 'Test1' then val end) test1,
max(case when test_name = 'Test2' then val end) test2,
max(case when test_name = 'Test3' then val end) test3
from (
select t.*, row_number() over(partition by sbno, test_name order by val) rn
from mytable t
) t
group by sbno, rn
order by sbno, rn
sbno |测试1 |测试2 |测试3
---: | :---- | :---- | :----
1 |一个 |乙| C
1 | D | 空 | 空
2 |一个 |乙| C
2 | D | 空 | 空
【讨论】:
这是一个使用row_number() 和PIVOT 的选项
示例
Select *
From (
Select *
,RowNr = (row_number() over (partition by SBNO order by VAL) -1 ) / 3
from YourTable
) src
Pivot (max(VAL) for Test_Name in ([Test1],[Test2],[Test3] ) ) pvt
Order By SBNO,RowNr
退货
SBNO RowNr Test1 Test2 Test3
1 0 A B C
1 1 D NULL NULL
2 0 A B C
2 1 D NULL NULL
【讨论】: