2012-11-30 107 views
0

我會盡我所能解釋我想要完成的工作。基於子集數據結果的SQL返回值

我有下面的數據子集的表:

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會返回「混合」。
  • 的2 BF_ID將返回 「C_ID_ATTRIB」
  • BF_ID 3將返回 「T_ID_ATTRIB」
+0

您使用哪種rdbms? – Khan

+0

我正在使用Boracle;) – KingKongFrog

+1

我不確定我是否理解爲什麼1的bf_id與3的bf_id不同。在'C_ID'和'C_ID'中都顯示非空數據'T_ID'列。但是應該返回「混合」,而另一個應該返回「T_ID_ATTRIB」。什麼是邏輯,讓你區分這兩個? –

回答

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 
+0

微小差異 – igr

+0

不能找到如何刪除評論...? – igr

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)

+0

啊,它失去了格式化,所以我失去了開始的論點,雖然... – igr