【问题标题】:SQL query to filter records based on count and status基于计数和状态过滤记录的 SQL 查询
【发布时间】:2020-07-27 12:35:29
【问题描述】:

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

数据库:Postgres

过滤条件:

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

如何为此编写 SQL 查询?

【问题讨论】:

  • 样本数据和期望的结果会有所帮助。
  • 请在下面查看我的答案。

标签: sql postgresql


【解决方案1】:

您可以尝试以下查询:

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 菲律宾比索

5 2 1 7 比索

【讨论】:

  • 请注意,您使用的语法是无效的标准 SQL,不适用于 Postgres
  • 我在SQL查询中给出了查询,请求者可以根据Postgre更改语法。
【解决方案2】:

嗯。 . .你似乎想要:

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;

【讨论】:

  • 在你的解决方案中,如果有Student_id的记录,学期相同但课程不同,那么我认为,它不会按照他的期望给出结果。
  • @RajeevKumar 。 . .我认为这符合您的描述。没有样本数据和期望的结果,很难说,是吗? SQL/DB fiddle 也会有所帮助。
  • 谢谢。你的建议拯救了我的一天 :) 我不得不对你的解决方案做一些改变,它按我的预期工作。
【解决方案3】:

CASE WHEN status='x' AND count>1 THEN 1 ELSE 0 END

【讨论】:

    猜你喜欢
    • 2022-11-03
    • 1970-01-01
    • 1970-01-01
    • 2023-02-26
    • 1970-01-01
    • 1970-01-01
    • 2022-01-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多