[英]Searching for missing or duplicated values in composite keys
Let's say I have a table with a two-part composite key like the following:假设我有一个包含两部分复合键的表,如下所示:
Key1 Key2 a char1 a char2 a char3 a char4 a char5 b char1 etc.
I need to check if there is a value form Key1 with missing or duplicated corresponding values from Key2 (ie values from key1 without 5 specific values from key2).我需要检查是否存在 Key1 的值,其中缺少或重复来自 Key2 的对应值(即来自 key1 的值没有来自 key2 的 5 个特定值)。 I'm new to sql, thanks in advance for help.我是 sql 的新手,在此先感谢您的帮助。
Sample data:样本数据:
SQL> select * From test order by key1, key2;
KEY1 KEY2
---- ----
a ch1
a ch2
a ch3
b ch1
c ch2
c ch3
6 rows selected.
One option is to一种选择是
[KEY1, KEY2]
combinations创建所有[KEY1, KEY2]
组合的交叉连接MINUS
set operator, find missing values in the source table使用MINUS
集合运算符,在源表中查找缺失值SQL> with
2 -- distinct keys
3 k1 as (select distinct key1 from test),
4 k2 as (select distinct key2 from test),
5 -- cross join makes all possible combinations
6 cj as
7 (select a.key1, b.key2
8 from k1 a cross join k2 b
9 )
10 -- MINUS set operator returns missing key combinations
11 select key1, key2 from cj
12 minus
13 select key1, key2 from test;
KEY1 KEY2
---- ----
b ch2
b ch3
c ch1
SQL>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.