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 server 2005。

4

3 回答 3

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

于 2012-12-16T00:42:46.300 回答
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
于 2012-12-14T22:44:02.650 回答
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 的建议是适用的,无论您想在一次查询中获得多少人的结果。

于 2012-12-16T01:25:37.580 回答