我有一个表,其中包含以下数据
ID | Col_2
A | 'ABC'
A | 'GHI'
A | null
B | 'null'
B | 'HJH'
B | 'NBN'
C | null我有两个案子要处理:
重复的I:在重复I的情况下,我只需要那些在col_2中没有null的I,例如,查询应该返回:
A | 'ABC'
A | 'GHI'
B | 'HJH'
B | 'NBN'非重复Id:如果是非重复id,则无论col_2中存在什么值,查询都应返回结果
因此,查询的最终结果应该是
ID | Col_2
A | 'ABC'
A | 'GHI'
B | 'HJH'
B | 'NBN'
C | null我已经成功地创建了以下查询,其中它满足重复的id情况,而不是非重复的情况。
查询:
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)应该在查询中进行哪些更改,以满足非重复的情况。
提前感谢!
发布于 2020-10-19 20:24:33
假设NULL是NULL而不是字符串,并且每个id只有一个NULL值,您可以这样做:
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值可以重复,并且只需要一行,则将其调整为:
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)的索引。
如果您只想要每个id的col_2值,可以在每一行上将它们连接起来:
select id, group_concat(col_2)
from t
group by id;另一种选择是使用窗口函数:
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;https://stackoverflow.com/questions/64427254
复制相似问题