这两个表都已存在,因此不寻找动态情况。目标是水平合并数据行,但将它们放在最左边的数据行中#34;现场可用。永远不会有第四个条目。
我正在使用Microsoft SQL Server
表1:
ID|Data
--------
A | 1
A | 2
B | 3
C | 4
C | 5
C | 6
表2:
ID | Data 1 | Data 2 | Data 3
------------------------------
A | | |
B | | |
C | | |
表2的期望结果:
ID | Data 1 | Data 2 | Data 3
------------------------------
A | 1 | 2 |
B | 3 | |
C | 6 | 7 | 8
答案 0 :(得分:0)
您可以使用row_number
:
select id,
max(case when rn = 1 then data end) as data_1,
max(case when rn = 2 then data end) as data_2,
max(case when rn = 3 then data end) as data_3
from (
select t.*,
row_number() over (
partition by id order by data
) as rn
from your_table t
) t
group by id;