根据多个表中的最大(日期)选择记录

时间:2012-12-14 21:55:04

标签: tsql sql-server-2005 max

我有两张表:1表示初步评估,1表示重新评估。格式如下:

initialAssessment

  • assessmentId
  • personId
  • assessmentDate
  • totalScore

Reassessments

  • assessmentId
  • personId
  • assessmentDate
  • totalScore

每张桌子每人包含1条记录。最新评估可能未包含在重新评估表中。出于这个原因,我需要选择两个表之间的最新评估以及给定人员的相应总分。我尝试了以下查询,但我得到了多行:

 SELECT personId, MAX(assessmentDate) AS maxSubmittedDt, TotalScore
 FROM (
    SELECT personId, assessmentDate, TotalScore
    FROM  initialAssessment
    WHERE personId = 1
    UNION
    SELECT personId, assessmentDate, TotalScore
    FROM Reassessments
    WHERE personId = 1) AS u
 Group BY personId, TotalScore
 Order By personId

我的问题是,我如何选择最新的评估及其在初步评估和重新评估表之间的相应分数?如果重要,我正在使用SQl服务器2005。

3 个答案:

答案 0 :(得分:3)

SELECT personId, assessmentDate, TotalScore
FROM (
     SELECT personId, assessmentDate, TotalScore, ROW_NUMBER() OVER (Partition by personId Order by assessmentDate desc) as RowId
     FROM (
        SELECT personId, assessmentDate, TotalScore
        FROM  initialAssessment
        WHERE personId = 1
        UNION
        SELECT personId, assessmentDate, TotalScore
        FROM Reassessments
        WHERE personId = 1
      ) a
) b
WHERE RowId = 1

这将是这样的。

http://www.codeproject.com/Articles/308281/How-to-Use-ROW_NUMBER-to-Enumerate-and-Partition-R

答案 1 :(得分:0)

我注意到您的SQL不应用您从嵌套联合创建的别名“u”。此外,您的主要选择不应用在下面的Group By中应用的personId。请尝试以下方法:

SELECT u.personId AS offenderCD, MAX(u.assessmentDate) AS maxSubmittedDt, u.TotalScore
FROM (
SELECT personId, assessmentDate, TotalScore
FROM  initialAssessment
WHERE personId = 1

UNION

SELECT personId, assessmentDate, TotalScore
FROM Reassessments
WHERE personId = 1) AS u
Group BY u.personId, u.assessmentDate, u.TotalScore
Order By u.personId

答案 2 :(得分:0)

如果您只想查询一个人,可以使用TOP(n)+ ORDER BY:

SELECT TOP (1) personId, assessmentDate, TotalScore
FROM (
    SELECT personId, assessmentDate, TotalScore
    FROM  initialAssessment
    WHERE personId = 1
    UNION
    SELECT personId, assessmentDate, TotalScore
    FROM Reassessments
    WHERE personId = 1) AS u
) s
ORDER BY assessmentDate DESC
;
但是,无论您希望在一个查询中获得多少人的结果,

@Brian White's suggestion都适用。