首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从col_2不为空的表中选择id(重复id)

从col_2不为空的表中选择id(重复id)
EN

Stack Overflow用户
提问于 2020-10-19 20:22:00
回答 1查看 48关注 0票数 0

我有一个表,其中包含以下数据

代码语言:javascript
复制
ID | Col_2
A  | 'ABC'
A  | 'GHI'
A  | null
B  | 'null'
B  | 'HJH'
B  | 'NBN'
C  | null

我有两个案子要处理:

重复的I:在重复I的情况下,我只需要那些在col_2中没有null的I,例如,查询应该返回:

代码语言:javascript
复制
A  | 'ABC'
A  | 'GHI'
B  | 'HJH'
B  | 'NBN'

非重复Id:如果是非重复id,则无论col_2中存在什么值,查询都应返回结果

因此,查询的最终结果应该是

代码语言:javascript
复制
ID | Col_2
A  | 'ABC'
A  | 'GHI'
B  | 'HJH'
B  | 'NBN'
C  | null

我已经成功地创建了以下查询,其中它满足重复的id情况,而不是非重复的情况。

查询:

代码语言:javascript
复制
select id,col_2 
from mytable
group by id,col_2
having (sum(case when col_2 is not null then 1 else 0 end) > 0)

应该在查询中进行哪些更改,以满足非重复的情况。

提前感谢!

EN

回答 1

Stack Overflow用户

发布于 2020-10-19 20:24:33

假设NULLNULL而不是字符串,并且每个id只有一个NULL值,您可以这样做:

代码语言:javascript
复制
select t.*
from t
where t.col_2 is not null or
      not exists (select 1 from t t2 where t2.id = t.id and t2.col_2 is not null);

如果您的null值可以重复,并且只需要一行,则将其调整为:

代码语言:javascript
复制
select t.*
from t
where t.col_2 is not null 
union all
select distinct t.*
from t
where not exists (select 1 from t t2 where t2.id = t.id and t2.col_2 is not null);

Here是一个db<>fiddle。

为了提高性能,您需要一个关于(id, col_2)的索引。

如果您只想要每个idcol_2值,可以在每一行上将它们连接起来:

代码语言:javascript
复制
select id, group_concat(col_2)
from t
group by id;

另一种选择是使用窗口函数:

代码语言:javascript
复制
select t.id, col_2
from (select t.*,
             rank() over (partition by id order by col_2 is not null desc) as seqnum
      from t
     ) t
where seqnum = 1;
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64427254

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档