[英]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 因此,我想获取Previous_Ranking中所有未出现在Current_Ranking中的记录(意味着新ID),以及所有它们在Previous_Ranking中的排名与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. 我正在使用BigQuery,因此可以使用本机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). 注意:
RANK
是许多版本的SQL中的保留关键字(尽管在BigQuery中显然不是)。 So, you might want to avoid using RANK
as a name for columns and tables. 因此,您可能要避免使用
RANK
作为列和表的名称。
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
: 您还可以使用
EXCEPT
:
select pr.*
from previous_ranking
except distinct
select r.*
from ranking;
Or not exists
: 还是
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. 我发现这两个版本都比
left join
版本更清晰。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.