Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.1k views
in Technique[技术] by (71.8m points)

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?

I have a table that consists of the following:

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

I would like to see which ID values are align per team (AB & DC both have the same ID present). There are going to be some NULLs/Mismatches due to the size of TEAM AB being 1 million and size of TEAM DC being 50k.

I tried this but doesn't have another Field ID to compare

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

My desired output is a new table that shows the fields 'Team' and 'ID' and the third column that shows if they matched or not.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you want to get teams that have the same ids, then you can use 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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...