问题:
准备数据:
create table students1(
student_id int not null , -- 学生id
dpt varchar(50) not null, -- 学院
sbmt_at timestamp with time zone -- 提交时间
);
insert into students1(student_id, dpt, sbmt_at)
values(100, '理学院', 'now()'),
(101, '理学院', 'now()'),
(102, '文学院', null),
(103, '文学院', 'now()'),
(104, '文学院', 'now()'),
(105, '文学院', null),
(106, '工学院', null),
(107, '经济学院', 'now()');
问题: 找出所有sbmt_at(提交时间)不为空的dpt(学院)
解答
利用count的特性查找:
select dpt
from students1
group by dpt
having count(*) = count(sbmt_at);
/*
🤓count(*)与count(col_name)除了性能上的差别,就是
count(*)统计的是行数, 不过滤null,
count(col_name)统计的是字段不为null的行数, 要过滤掉null
*/
使用count与case写的特征表达式查找:
select dpt
from students1
group by dpt
having count(*) = sum(case when sbmt_at is null then 0 else 1 end);