PostgreSQL 查询列出表之间共有的列的所有值

PostgreSQL query to list all values of a column that are common between tables

我有一个名为 endate 的列(其值是日期)出现在五个 table 中,straddle0, straddle1, straddle2, straddle3 and straddle4。我对数据的假设是,一个 table 的 endate 值不存在于任何其他提到的 table 中(尽管可以在同一个 table 中重复).但为了确认,我想列出可能出现在多个 table 中的所有 endate 值(例如 01-01-2017 出现在 straddle0 中,也出现在 straddle402-02-2017 出现在 straddle1 以及 straddle3straddle5) 中。

相同的 PostgreSQL 查询是什么?

不确定您想要哪种格式的结果。我制作了两个脚本 - 一个简单的和一个更详细的。也许这就是你需要的

Here is dbfiddle

我会使用 UNION ALLGROUP BY/HAVING:

架构 (PostgreSQL v13)

CREATE TABLE t1 (
    enddate date
);

CREATE TABLE t2 (
    enddate date
);

CREATE TABLE t3 (
    enddate date
);

INSERT INTO t1
VALUES (CURRENT_DATE), (CURRENT_DATE+1);

INSERT INTO t2
VALUES (CURRENT_DATE), (CURRENT_DATE+2), (CURRENT_DATE+2);

INSERT INTO t3
VALUES (CURRENT_DATE+2), (CURRENT_DATE+3);

查询 #1

WITH all_dates AS (
    SELECT 't1' AS table_name, enddate
    FROM t1
    UNION ALL
    SELECT 't2' AS table_name, enddate
    FROM t2
    UNION ALL
    SELECT 't3' AS table_name, enddate
    FROM t3
)
SELECT enddate, ARRAY_AGG(DISTINCT table_name) AS appears_in
FROM all_dates
GROUP BY 1
HAVING COUNT(DISTINCT table_name) > 1
ORDER BY 1;
enddate appears_in
2022-05-07T00:00:00.000Z t1,t2
2022-05-09T00:00:00.000Z t2,t3

View on DB Fiddle

with data(dt, t) as (
    select distinct endate, 0 from straddle0 union all
    select distinct endate, 1 from straddle1 union all
    select distinct endate, 2 from straddle2 union all
    select distinct endate, 3 from straddle3 union all
    select distinct endate, 4 from straddle4
)
select dt, min(t) as t from data group by dt having count(*) = 1;