gpt4 book ai didi

sql - 在 SQL 中选择具有最密集(最少 NULL)列数据的行

转载 作者:行者123 更新时间:2023-12-04 01:46:48 26 4
gpt4 key购买 nike

我有多个重复的 ID,需要将其缩减为一个值。通常我会使用聚合方法来组合列值(作为总和、平均值等)。在这里,我感兴趣的是只保留所有列中具有最多非空值的行:

鉴于此表:

id   col1   col2   col3
1 a '' ''
1 a b ''
2 x y ''
1 a b c
2 s '' ''

我如何选择:
id   col1   col2   col3
2 x y ''
1 a b c

最佳答案

有了这个查询:

select id, 
max(
(case when col1 is not null then 1 else 0 end) +
(case when col2 is not null then 1 else 0 end) +
(case when col3 is not null then 1 else 0 end)
) maxnotnulls
from tablename
group by id

您可以为每个 id 获取每个 id 的最大非空列数。
因此,您可以使用上述查询加入表,如下所示:
select t.* from tablename t
inner join (
select id,
max(
(case when col1 is not null then 1 else 0 end) +
(case when col2 is not null then 1 else 0 end) +
(case when col3 is not null then 1 else 0 end)
) maxnotnulls
from tablename
group by id
) g
on
g.id = t.id
and
(case when t.col1 is not null then 1 else 0 end) +
(case when t.col2 is not null then 1 else 0 end) +
(case when t.col3 is not null then 1 else 0 end) = g.maxnotnulls

关于sql - 在 SQL 中选择具有最密集(最少 NULL)列数据的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54973285/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com