Teradata SQL中COUNT(DISTINCT)条件查询无结果问题求助
问题排查与解决
原查询无结果的原因
你写的SQL同时按id和type分组,每个分组里的type都是唯一值,所以count(distinct type)的结果必然是1,永远满足不了>1的条件,自然返回空结果。
正确写法(匹配你的预期输出)
如果要找出拥有多种不同type的id,并返回这些id对应的所有type记录,有两种高效写法:
- 方法1:子查询筛选符合条件的id
select t.id, t.type from table1 t where t.id in ( select id from table1 where id in (100, 101) group by id having count(distinct type) > 1 );
- 方法2:窗口函数实现(Teradata支持)
select id, type from ( select id, type, count(distinct type) over (partition by id) as type_cnt from table1 where id in (100, 101) ) t where t.type_cnt > 1;
如果你的需求只是找出符合条件的id及对应的不同type数量,用以下SQL即可:
select id, count(distinct type) as distinct_type_count from table1 where id in (100, 101) group by id having count(distinct type) > 1;
内容的提问来源于stack exchange,提问作者user13948791
相关产品推荐
相关产品推荐

