我有两个表,它们有"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发布于 2020-04-18 19:13:35
如果标签不多,则可以进行条件聚合:
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;如果表中有更多的标签,那么你就需要动态透视。
发布于 2020-04-18 20:00:10
我不建议将每个标记放在单独的列中。另一种方法是将标记合并到单个列中。
例如:
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的最大标记数。
https://stackoverflow.com/questions/61288112
复制相似问题