简体   繁体   中英

How to compare two snaps of schema data in SQL?

I have two tables:

Current_Ranking:

id   rank
1     20
2     25
3     26
4     17

Previous_Ranking

id rank
1   20
2   26
3   18
4   17
5   5

I want to get as a result all records in Previous_Ranking that don't appear in Current_Ranking (means new id) and all records that their rank in Previous_Ranking is not the same as Current_Ranking

So expected result is:

id rank
2   26
3   18
5   5

How can I do that? I know I can do:

    SELECT   p.id, p.rank
    FROM     Previous_Ranking p
       LEFT JOIN Current_Ranking c USING (id)
    WHERE    c.id IS NULL

This should give me all the new rows. But How I continue from here?

I'm using BigQuery so this can be done with native SQL.

You may use a left join with two criteria:

SELECT p.id, p.rank
FROM Previous_Ranking p
LEFT JOIN Current_Ranking c
    ON p.id = c.id
WHERE
    c.id IS NULL OR p.rank <> c.rank;

在此处输入图片说明

Note: RANK is a reserved keyword in many versions of SQL (though apparently not in BigQuery). So, you might want to avoid using RANK as a name for columns and tables.

I would simply do:

select p.id, p.rank
from Previous_Ranking p
left join Current_Ranking c 
   ON p.id = c.id
where p.c is null
   OR p.rank !=  c.rank

You can also use EXCEPT :

select pr.*
from previous_ranking
except distinct
select r.*
from ranking;

Or not exists :

select pr.*
from previous_ranking pr
where not exists (select 1
                  from ranking r
                  where r.id = pr.id and r.rank = pr.rank
                 );

I find both of these clearer than a left join version.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM