2017-04-12 68 views
0

enter image description here入住另一列(NULL或NOT NULL)和所有的值返回唯一記錄

正如你看到的CID = 1所有日期字段都爲NULL和CID = 3的所有日期字段不爲空。

如果所有日期都爲NULL,那麼使用「NULL」,如果所有日期都不是NULL,那麼使用「NOT NULL」,我需要使用新字段獲得唯一的cids。

cid - new field 
1 - NULL 
3 - NOT NULL 
+0

請考慮增加樣本表中的數據和格式化文本預期的結果。 同時向我們顯示您當前的查詢嘗試 – TheGameiswar

+0

您正在使用哪個數據庫。 – Utsav

+0

我使用postgreSQL –

回答

2

您可以通過聚集和case做到這一點:

select cid, 
     (case when count(datecol) = 0 then 'NULL' 
      when count(datecol) = count(*) then 'NOT NULL' 
     end) as newField 
from t 
group by cid 
having count(datecol) in (0, count(*)); 
+0

非常感謝 –

2
select cid, case when min(c) = 0 AND max(c) = 0 then 'null' when min(c) = 1 and max(c) = 1 then 'not null' end from (
    select cid, case when dt is null then 0 else 1 end as c from your_table 
) t 
group by cid 
having min(c) = max(c)