gpt4 book ai didi

sql - 仅选择 "most complete"记录

转载 作者:行者123 更新时间:2023-11-29 12:16:05 25 4
gpt4 key购买 nike

我需要解决以下问题。

假设我有一个包含 4 个字段的表,分别称为 a、b、c、d。

我有以下记录:

-------------------------------------
a | b | c | d
-------------------------------------
1 | 2 | | row 1
1 | 2 | 3 | 4 row 2
1 | 2 | | 4 row 3
1 | 2 | 3 | row 4

可以观察到,第 1、3、4 行是第 2 行的“子记录”。

我想做的是,只提取第二行。

你能帮帮我吗?

预先感谢您的回答

编辑:我需要更具体一些。

我也可以有案例:

-------------------------------------
a | b | c | d
-------------------------------------
1 | 2 | | row 1
1 | 2 | | 4 row 2
1 | | | 4 row 3

我需要提取第二行的地方,

-------------------------------------
a | b | c | d
-------------------------------------
1 | 2 | | row 1
1 | 2 | 3 | row 2
1 | | 3 | row 3

我需要再次提取第二行。

夫妻同理,


   a   |    b    |    c    |    d  
-------------------------------------
1 | | | row 1
1 | | 3 | row 2
| | 3 | row 3

其他例子依此类推。

(当然,现在总是第2行)

最佳答案

使用 NOT EXISTS 可以过滤掉具有更好重复的记录。

create table abcd (
a int,
b int,
c int,
d int
);
insert into abcd (a, b, c, d) values
(1, 2, null, null)
,(1, 2, 3, 4)
,(1, 2, null, 4)
,(1, 2, 3, null)

,(2, 3, null,null)
,(2, 3, null, 5)
,(2, null, null, 5)

,(3, null, null, null)
,(3, null, 5, null)
,(null, null, 5, null)
SELECT *  
FROM abcd AS t
WHERE NOT EXISTS
(
select 1
from abcd as d
where (t.a is null or d.a = t.a)
and (t.b is null or d.b = t.b)
and (t.c is null or d.c = t.c)
and (t.d is null or d.d = t.d)
and (case when t.a is null then 0 else 1 end +
case when t.b is null then 0 else 1 end +
case when t.c is null then 0 else 1 end +
case when t.d is null then 0 else 1 end) <
(case when d.a is null then 0 else 1 end +
case when d.b is null then 0 else 1 end +
case when d.c is null then 0 else 1 end +
case when d.d is null then 0 else 1 end)
);
 a |    b |    c |    d-: | ---: | ---: | ---: 1 |    2 |    3 |    4 2 |    3 | null |    5 3 | null |    5 | null

db<> fiddle here

关于sql - 仅选择 "most complete"记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53485031/

25 4 0