我会尽力解释我想要完成的事情。
我有一个包含以下数据子集的表:
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的行数可能是无限的。
答案 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)