如何在SQL Server查询中将id相似的不同行结果转换为id唯一的不同列



我有两个具有"1:*"关系的表。我想连接两个表,并将id相似的所有行合并为一行和具有相同行值的不同列。

为了我在ssms 17中的结果是:

table1.id    table2.tag 
------------------------
1            <value a>
1            <value b>
1            <value c>
2            <value d>
2            <value e>

我想要这个结果:

table1.id    C1.table2.tag    C2.table2.tag    C3.table2.tag
------------------------------------------------------------
1            <value a>        <value b>        <value c>
2            <value d>        <value e>        null

如果标签不多,则可以执行条件聚合:

select id, 
max(case when seq = 1 then tag end) as tag_1,
max(case when seq = 2 then tag end) as tag_2,
max(case when seq = 3 then tag end) as tag_3
from (select t1.id, t2.*, row_number() over (partition by t1.id order by t2.tag) as seq
from table1 t1 inner join
table2 t2
on t2.id = t1.id
) t
group by id;

若表有更多的标记,那个么就需要动态数据透视。

我不建议将每个标记放在单独的列中。另一种选择是将标记组合成一列。

例如:

select t1.table1_id,
string_agg(t2.tag, ',') as tags
from table1 t1 join
table2 t2
on t2.id = t1.table2_id
group by t1.table1_id;

这样,您就不必担心给定id或使用动态SQL的最大标记数。

最新更新