两个表,t1 和 t2
表:t1
id name age
-- ---- ---
1 sue 33
2 jane 25
3 ann 40
4 lucy 21
表:t2
id sister brother
-- ------ -------
1 sue frank
2 sue bob
3 jane bill
4 ann harry
5 ann dave
我想在 t1 上LEFT 加入 t2,在 name=sister 上,但不是由此产生的通常输出,每个姐妹有多行,他们有多个兄弟,我希望结果看起来像:
id name age brother_1 brother_2
-- ---- --- --------- ---------
1 sue 33 frank bob
2 jane 25 bill
3 ann 40 harry dave
4 lucy 21
为了这个例子的目的,假设一个姐姐永远不会有超过 2 个兄弟。
我什至不太确定如何描述我在这里尝试做的事情,它“感觉”像是一种支点?,但我找不到另一个符合我的问题/答案,(抱歉如果网站上已经存在答案但我没有发现,请提前通知)
我正在使用 Postgresql 9.5。
最佳答案
一种选择是使用 ROW_NUMBER
和数据透视查询来处理您的要求:
WITH cte AS (
SELECT t1.id, t1.name, t1.age, t2.brother,
ROW_NUMBER() OVER (PARTITION BY t1.id ORDER BY t2.id) rn
FROM table1 t1
LEFT JOIN table2 t2
ON t1.name = t2.sister
)
SELECT
id,
name,
age,
MAX(brother) FILTER (WHERE rn = 1) brother_1,
MAX(brother) FILTER (WHERE rn = 2) brother_2
FROM cte
GROUP BY
id,
name,
age
ORDER BY
id;
Demo
关于sql - Postgresql - 加入两个表,其中结果有附加列,其中值来自 t2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58515866/