为每个“订单”选择最近日期的记录

时间:2010-12-06 16:11:48

标签: sql tsql

我有以下样本表格式的信息。每个文件可以有多个等级,我需要为每个文件选择最新等级(基于完成日期)。如果有一个文件w /相同的完成日期,我会选择最好的成绩(最好的和后续的字母是较低的成绩)。这似乎很容易,但出于某种原因有脑屁

样本表:

ID_PK File_No Grade Completion_Date

1 Smith A 10/1/2010

2 Smith C 9/25/2010

3 Davis B 11/1/2010

4 Johnson D 12/5/2010

5 Johnson A 11/1/2010

6 Johnson C 10/1/2010

7 Miller X 9/1/2010

8 Miller F 12/1/2010

9 Miller D 10/1/2010

理想的结果:

1 Smith A 10/1/2010

3 Davis B 11/1/2010

4 Johnson D 12/5/2010

8 Miller F 12/1/2010

3 个答案:

答案 0 :(得分:2)

使用WINDOWING功能更有效,也更简单

with cte AS(
select  '1' AS ID_no,'Smith' AS FILE_NO,'A' AS GRADE,
CAST('10/1/2010' AS DATE) AS CREATION_DATE
union all 
select '2','Smith','C','9/25/2010'
union all 
select '3','Davis','B','11/1/2010'
union all 
select '4','Johnson','D','12/5/2010'
union all 
select '5','Johnson','A','11/1/2010'
union all 
select '6','Johnson','C','10/1/2010'
union all 
select '7','Miller','X','9/1/2010'
union all 
select '8','Miller','F','12/1/2010'
union all 
select '9','Miller','D','10/1/2010')


SELECT X.ID_NO,X.FILE_NO,X.GRADE,X.CREATION_DATE FROM(
SELECT ID_NO,FILE_NO,GRADE,CREATION_DATE ,
ROW_NUMBER() OVER(PARTITION BY FILE_NO ORDER BY CREATION_DATE DESC,GRADE ASC ) AS RN
FROM CTE)AS X
WHERE X.RN=1
ORDER BY ID_NO

答案 1 :(得分:1)

试试这个(未经测试):

select max_grade.*
from `Sample Table` st
inner join (
  select File_No, max(Completion_Date) as Completion_Date
  from `Sample Table`
  group by File_No
) max_date on st.Completion_Date = max_date.CompletionDate
inner join (
  select File_No, Completion_Date, max(Grade) as Grade
  from `Sample Table`
  group by File_No, Completion_Date
) max_grade on st.File_No = max_grade.File_No and st.Completion_Date = max_grade.Completion_Date

请注意,您可能需要修改特定数据库的语法和表名。

答案 2 :(得分:0)

我用示例数据创建了一个表。我针对表测试了以下查询,一切似乎都正常工作并匹配了示例结果。


SELECT 
    ID_PK,
    StudentGrade.File_No, 
    MIN(StudentGrade.Grade), 
    StudentGrade.Completion_Date
FROM
(
    SELECT File_No, MAX(Completion_Date) Completion_Date
    FROM StudentGrade
    GROUP BY File_No
) Student
INNER JOIN StudentGrade ON
    Student.File_No = StudentGrade.File_No 
    AND StudentGrade.Completion_Date = Student.Completion_Date
GROUP BY ID_PK, StudentGrade.File_No, StudentGrade.Completion_Date
ORDER BY ID_PK