检查另一列中的所有值(NULL或NOT NULL)并返回唯一记录

时间:2017-04-12 10:32:18

标签: sql

enter image description here

如您所见,对于cid = 1,所有日期字段均为NULL,而对于cid = 3,所有日期字段均为NOT NULL。

我需要使用新字段获取唯一的cid,如果所有日期都为NULL,则为“NULL”,如果所有日期都为NOT NULL,则为“NOT NULL”。

cid - new field
1 - NULL
3 - NOT NULL

2 个答案:

答案 0 :(得分: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(*));

答案 1 :(得分: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)