SQL查询根据计数和状态过滤记录

时间:2020-07-27 12:35:29

标签: sql postgresql

计数超过1时,我必须根据状态过滤记录。 列名:Student_id,状态,学期和课程。

DB:Postgres

要过滤的条件:

  1. 如果仅存在一个学生记录,则状态(是或否)无关紧要。获取记录。
  2. 如果一个学生的记录数大于一个,则仅获取状态为真的那些学生。 (一条以上的记录意味着相同的Student_id,学期和课程)。在任何给定时间,只有一条记录的状态为true。

如何为此编写SQL查询?

3 个答案:

答案 0 :(得分:0)

嗯。 。 。您似乎想要:

select t.*
from (select t.*, count(*) over (partition by student_id) as cnt
      from t
     ) t
where cnt = 1 or status;

这会过滤掉记录多于一个且状态不是true的学生。

如果您真的希望每个学生一行,甚至没有真实身份的学生,也可以使用distinct on

select distinct on (student_id) t.*
from t
order by student_id, status desc;

答案 1 :(得分:0)

当status ='x'并且计数> 1然后1否则0结束的情况

答案 2 :(得分:0)

您可以尝试以下查询:

Create Table #TableA(
id int,
Student_id Varchar(100),
[Status] bit,
term int,
course varchar(10)
)

Insert Into #TableA Values(1, 1, 1, 3, 'C#')
Insert Into #TableA Values(2, 2, 0, 6, 'Php')
Insert Into #TableA Values(3, 2, 0, 6, 'Php')
Insert Into #TableA Values(4, 2, 1, 6, 'Php')
Insert Into #TableA Values(5, 2, 1, 7, 'Php')

Select a.id, a.Student_id, a.Status, a.term, a.course from 
(
Select *, count(*) over (Partition By Student_id, term, course) As row_count From #TableA
) a
Where a.row_count = 1 Or a.[Status] = 1

结果如下:

id Student_id状态学期课程

1 1 1 3 C#

4 2 1 6 Php

5 2 1 7 Php

相关问题