SQL返回值基于子集数据的结果

时间:2012-11-30 18:47:25

标签: sql oracle case

我会尽力解释我想要完成的事情。

我有一个包含以下数据子集的表:

ID    BF_ID    C_ID    T_ID
1     1        10000   182
2     1        230     null
3     2        123     null
4     3        10000   124

基本上我想基于BF_ID查询此表,以查看是否存在结果中存在非空T_ID和非空C_ID的数据。

在上面的例子中,我想区分不同BF_ID之间的查询。 BF_id的行数可能是无限的。

  • BF_ID为1将返回“mixed”。
  • BF_ID为2将返回“C_ID_ATTRIB”
  • 3的BF_ID将返回“T_ID_ATTRIB”

2 个答案:

答案 0 :(得分:0)

您只需要一个group by和case语句:

select bf_id,
       (case when count(t_id) = 0 and count(c_id) = 0 then 'Neither'
             when count(t_id) > 0 and count(c_id) = 0 then 'T_ID_ATTRIB'
             when count(t_id) = 0 and count(c_id) > 0 then 'C_ID_ATTRIB'
             else 'Mixed'
        end) as WhichAttribute
from t
group by bf_id

答案 1 :(得分:0)

Gordon提供的另一个示例替代方案,可能更具可读性: (只是输入没有测试) select bf_id, case when c is null and t is null then 'neither' when c is null and t is not null then 'T_ID_ATTRIB' when c is not null and t is null then 'C_ID_ATTRIB' else 'mixed' as which_attr from ( select bf_id, max(c_id) c, max(t_id) t from table1 group by bf_id)

相关问题