如何比较SQL中模式数据的两个快照?
我有两张桌子: 目前的排名:如何比较SQL中模式数据的两个快照?,sql,google-bigquery,Sql,Google Bigquery,我有两张桌子: 目前的排名: id rank 1 20 2 25 3 26 4 17 以前的排名 id rank 1 20 2 26 3 18 4 17 5 5 因此,我想获得上一次排名中没有出现在中的所有记录 当前_排名(表示新id)和所有记录,表明其在上一个_排名中的排名与当前_排名不同 因此,预期结果是: id rank 2 26 3 18 5 5 我该怎么做? 我知道我能做到: 选择p.id,p.rank 从之前的
id rank
1 20
2 25
3 26
4 17
以前的排名
id rank
1 20
2 26
3 18
4 17
5 5
因此,我想获得上一次排名中没有出现在中的所有记录
当前_排名(表示新id)和所有记录,表明其在上一个_排名中的排名与当前_排名不同
因此,预期结果是:
id rank
2 26
3 18
5 5
我该怎么做?
我知道我能做到:
选择p.id,p.rank
从之前的排名p
使用(id)左键连接当前_排名c
其中c.id为NULL
这应该给我所有的新行。但我如何从这里继续
我使用的是BigQuery,因此可以使用本机SQL完成此操作。您可以使用带有两个条件的左连接:
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;
选择p.id,p.rank
从之前的排名p
左连接当前_排名c
在p.id=c.id上
哪里
c、 id为NULL或p.rank c.rank;
注意:
RANK
在许多SQL版本中都是保留关键字(尽管在BigQuery中显然不是)。因此,您可能希望避免使用RANK
作为列和表的名称。您可以使用具有两个条件的左联接:
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;
选择p.id,p.rank
从之前的排名p
左连接当前_排名c
在p.id=c.id上
哪里
c、 id为NULL或p.rank c.rank;
注意:RANK
在许多SQL版本中都是保留关键字(尽管在BigQuery中显然不是)。因此,您可能希望避免使用RANK
作为列和表的名称
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
我只想:
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
您也可以使用
,除了
:
select pr.*
from previous_ranking
except distinct
select r.*
from ranking;
或不存在
:
select pr.*
from previous_ranking pr
where not exists (select 1
from ranking r
where r.id = pr.id and r.rank = pr.rank
);
我发现这两个版本都比
左连接版本更清晰 除了
,您还可以使用:
select pr.*
from previous_ranking
except distinct
select r.*
from ranking;
或不存在
:
select pr.*
from previous_ranking pr
where not exists (select 1
from ranking r
where r.id = pr.id and r.rank = pr.rank
);
我发现这两个版本都比左连接版本更清晰