You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 18:18:15