如何比较同一个 table 中的两个字段以查看它们是否匹配、不匹配或 SQL 中的两个 NULL 与 Group By?

How to compare two fields in the same table to see if they match, don't match, or both NULL in SQL with Group By?

我有一个 table 包含以下内容:

Team            ID             
--              --
AB             100001
DC             100001
DC             100032
AB             100021
AB             100032
AB             100044
DC             100044
DC             100323

我想查看每个团队的哪些 ID 值是一致的(AB 和 DC 都具有相同的 ID)。由于 TEAM AB 的大小为 100 万,TEAM DC 的大小为 50k,因此会有一些 NULLs/Mismatches。

我试过了,但没有其他字段 ID 可以比较

SELECT Team, ID FROM Table
WHERE ID IN
(
SELECT ID FROM Table
)

我想要的输出是一个新的 table,显示字段 'Team' 和 'ID',第三列显示它们是否匹配。

AB         DC           MATCH
--         --            --
100001     100001       TRUE
100032     100032       TRUE
100044     100044       TRUE
100021     100323       FALSE

如果你想获得相同id的队伍,那么你可以使用listagg():

select ids, listagg(team, ',') within group (order by team) as teams
from (select team, listagg(id, ',') within group (order by id) as ids
      from t
      group by team
     ) t
group by ids
having count(*) > 1;

显然您需要完整的外部联接:

with data as  (
    select 'ab' team, 100 id
    union all select 'ab', 101
    union all select 'ab', 102
    union all select 'cd', 102
    union all select 'cd', 101
    union all select 'cd', 105
)

select a.id ab, b.id cd, ifnull(a.id=b.id, false) match
from (select team, id from data where team='ab') a
full outer join (select team, id from data where team='cd') b
on a.id=b.id