sql - SQL Query 查找一张表中行的差异
问题描述
假设我有下表:
ID | CMP1 | CMP2 | CMP3 | FK1
------------------------------
1 | x | x | x | 1
2 | y | y | y | 1
3 | z | z | z | 1
------------------------------
4 | a | a | a | 2
5 | a | a | a | 2
6 | c | c | c | 2
------------------------------
7 | s | u | v | 3
8 | s | u | i | 3
9 | s | u | z | 3
现在我必须编写一个查询,返回 FK1 引用但在 CMP1-3 中具有不同值的所有 ID。
例子:
- 对于 ID 1-3,查询必须返回 1,2,3。
- 对于 ID 4-6,查询必须返回 6。
- 对于 ID 7-9,查询必须返回 7,8,9。
我知道我必须自行加入表格,但我无法比较按 FK1 分组的值 - 请帮助!
谢谢
解决方案
您似乎想要 (cmp1, cmp2, cmp3, fk1) 的值是唯一的行。您可以使用窗口功能:
select t.*
from (select t.*,
count(*) over (partition by cmp1, cmp2, cmp3, fk1) as cnt
from t
) t
where cnt = 1;
另一种方法使用not exists
:
select t.*
from t
where not exists (select 1
from t t2
where t2.fk1 = t.fk1 and
t2.cmp1 = t.cmp1 and
t2.cmp2 = t.cmp2 and
t2.cmp3 = t.cmp3 and
t2.id <> t.id
);
也就是说,没有其他行具有相同的(fk1, cmp1, cmp2, cmp3)
组合 - 和不同的id
.
推荐阅读
- oracle - JMeter 5.2.1 - 连接属性被忽略
- servicestack - 带有 emitLowercaseUnderscoreNames = true 的 Servicestack JsConfig 不适用于具有字母数字名称的属性
- git - 如何获取最新创建的远程 Git 分支列表?
- go - 在 Couchbase 中插入只读文档
- docker - 如何停止docker自动启动jupyter笔记本
- angular - 我使用 canDeactive 时如何使用 Skiplocation
- java - 在 Java 中使用下一行打印字符串(斑马线模式)
- google-chrome - 与 http://local ip/ 上的跨站点资源关联的 cookie 被设置为没有 `SameSite` 属性
- wordpress - 如何确保在 Wordpress 中进行缓存
- django - 获取验证错误字段不能为空,即使模型中的 null=True