2017-03-02 6 views
1

私はデータベースの学生データを持つ学校システムで働いています。少なくとも毎年(場合によっては年に数回)、新しい「文書」を表すその学生のための新しい行のデータが作成されます。その行が他の基準を満たしていれば、その学生の最新の行の情報を取得するためのクエリを作成しようとしています(例えば、 'compsped'タイプである必要があり、 'F'また​​は 'I ')。私が以下に書いたクエリを実行すると、かなりうまくいくが、データが不足しているようだ。私はいくつかのデータが欠けている理由は、それが最新のドキュメントを最初に探しているので、それは他の基準を満たさないドキュメントを除外しているからです。代わりに、私はまず最初に他の基準を満たさない文書を除外し、そのリストから最新の行をそのリストから取り出すことを望みます。私たちはSQL Server 20016を使用しています。質問がない場合は質問してください。ありがとう!SQLクエリ:他のパラメータで最新のものを取得しようとしています

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')) 

答えて

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 
+0

感謝なし。 – bosstone75

+0

@ bosstone75最初のクエリのエラーを修正しました。これは、最初のクエリのエラーを修正しました。 – SqlZim

+1

@SqlZim私はエディタでCTEを見上げるのに時間がかかりすぎて、あなたは私にそれを打ち負かしました:-) Haha!Upvoted。 – 3BK

関連する問題