sql - Postgresql - 加入两个表,其中结果有附加列,其中值来自 t2

标签 sql postgresql left-join

两个表,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;

screen capture of demo below

Demo

关于sql - Postgresql - 加入两个表,其中结果有附加列,其中值来自 t2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58515866/

相关文章:

仅限制记录子集的 SQL 查询

ruby-on-rails - 将两个 ActiveRecord 关联集合合并为单个关联集合

java - Flink 左外连接 : Enriching a Stream with Data from a csv file

database - 左加入 influxDB

sql - 将一个表中缺失的记录复制到新表中

php - 我将如何从 mysql 获取相同名称的值

c# - 使用绑定(bind)字段时如何更新 GridView

sql - 使用保留字时间戳作为字段名称 (Firebird 2.5)

python - 文件夹+数据库的备份 - Python

java - 错误 : syntax error at or near "INTEGER"