sql—在忽略postgresql上的列时使用group by的select语句

5m1hhzi4  于 2021-07-24  发布在  Java
关注(0)|答案(3)|浏览(355)

我在postgresql数据库中有一个表名“report”,比如:

Student Class Marks Observation_time
A        1     11    21/7/2020
A        2     13    18/7/2020   
B        1     19    17/7/2020
A        1     17    15/7/2020
B        1     15    21/7/2020
C        1     NAN     10/7/2015
C        1     NAN     11/7/2015
C        2     8     10/7/2015
C        2     0     11/7/2015
D        1     NAN     10/7/2015
D        1     NAN     11/7/2015
D        2     NAN     10/7/2015
D        2     NAN     11/7/2015

我想从上表中获得所有的行,对于特定的学生和班级,这些行的分数总是nan(不考虑观察时间)。
预期输出为:

student class
C       1
D       1
D       2

有人能帮我问一下吗?谢谢

ijxebb2r

ijxebb2r1#

如果要查找所有带有null in标记的行,请使用:

SELECT DISTINCT Student,Class
FROM report
WHERE Marks IS NULL;

..distinct运算符从结果中删除重复项
另一种变体是:

SELECT Student,Class
FROM report
GROUP BY Student,Class
HAVING COUNT(*)=COUNT(*)FILTER(WHERE Marks IS NULL)
zzlelutf

zzlelutf2#

我为你的问题举了个例子。

CREATE TABLE reportt (
  Class  int,
  Marks  int,
  Student  VARCHAR(100),
  Observation_time VARCHAR(100),
);

INSERT INTO reportt
  (Student, Class, Marks,Observation_time)
VALUES
  ('A',1,11,'21/7/2020'),
  ('A',2,13,'18/7/2020'),
  ('B',1,19,'17/7/2020'),
  ('A',1,17,'15/7/2020'),
  ('B',1,15,'21/7/2020'),
  ('C',1,null,'10/7/2015'),
  ('C',1,null,'11/7/2015'),
  ('C',2,8,'10/7/2015'),
  ('C',2,0,'11/7/2015'),
  ('D',1,null,'10/7/2015'),
  ('D',1,null,'11/7/2015'),
  ('D',2,null,'10/7/2015'),
  ('D',2,null,'11/7/2015')
  ;
with CTE_select as (
    select ISNULL(Marks,0) Marks, Student,Class 
    from  reportt 
  )
  select Student,Class,SUM(Marks) from CTE_select
  where marks >= 0
  group by Class,Student
  having   SUM(Marks)= 0;

结果=

Student Class
C        1  
D        1  
D        2
anhgbhbe

anhgbhbe3#

查看关于group by的文档,它非常强大,但也可能相当棘手。前面的答案(distinct)实际上也是一种groupby。我认为这应该得到你想要的结果,但请阅读文件,以了解正在发生的事情。

Select MIN(Student), MIN(Class)
  from report
where Marks = 0
  group by Student, Class

相关问题