SQL查询:尝试使用其他参数提取最新信息

时间:2017-03-02 19:58:38

标签: sql-server

我在学校系统中使用数据库中的学生数据。至少每年(有时一年多次)为该学生创建一行新的数据,代表一个新的“文档”。我正在尝试编写一个查询,以便在该行符合其他条件时为该学生提取最新的信息行(例如,它必须是“compsped”类型,并且需要具有“F”或“I”状态“)。当我运行下面写的查询时,它运行得很好,但似乎缺少一些数据。我认为它缺少一些数据的原因是因为它首先查找最新文档,然后它会过滤掉不符合其他标准的文档。相反,我希望它首先过滤掉不符合其他标准的文档,并希望它能从该列表中提取最新的行。我们正在使用SQL Server 20016.希望这是有道理的。如果没有,请提问。谢谢!

SELECT evaluationreports1.Status, 
evaluationreports1.EvalDueDate, 
evaluationreports1.EvalRptDate, 
evaluationreports1.StudentID, 
evaluationreports1.TypeAbbrev
FROM PlansAnoka.dbo.evaluationreports evaluationreports1
WHERE evalrptdate = (select max(evalrptdate) from evaluationreports where studentid = evaluationreports1.studentid) 
AND (evaluationreports1.TypeAbbrev='CompSpEd') 
AND (evaluationreports1.Status In ('F','I'))

1 个答案:

答案 0 :(得分:2)

对现有查询的这种修改可以起作用:

SELECT evaluationreports1.Status, 
evaluationreports1.EvalDueDate, 
evaluationreports1.EvalRptDate, 
evaluationreports1.StudentID, 
evaluationreports1.TypeAbbrev
FROM PlansAnoka.dbo.evaluationreports evaluationreports1
WHERE evalrptdate = (
  select max(evalrptdate) 
  from evaluationreports i 
  where i.studentid = evaluationreports1.studentid 
  and i.TypeAbbrev='CompSpEd'
  and i.Status In ('F','I')
  )

另一种方法是使用 row_number()

with common_table_expression as ()使用 row_number()

with cte as (
  select  *
      , rn = row_number() over (
              partition by studentid 
              order by evalrptdate desc
            )
    from PlansAnokt.dbo.evaluationreports t
    where t.TypeAbbrev='CompSpEd'
      and t.Status in ('F','I')
)
select *
  from cte
  where rn = 1

或没有cte

select *
  from (
    select  *
      , rn = row_number() over (
              partition by studentid 
              order by evalrptdate desc
            )
    from PlansAnokt.dbo.evaluationreports t
    where t.TypeAbbrev='CompSpEd'
      and t.Status in ('F','I')
      ) as cte
  where rn = 1
相关问题