计数超过1时,我必须根据状态过滤记录。 列名:Student_id,状态,学期和课程。
DB:Postgres
要过滤的条件:
如何为此编写SQL查询?
答案 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