SQL查询帮助 - 条件仅适用于最新记录

时间:2011-08-31 04:09:47

标签: sql sql-server sql-server-2005 tsql

以下是表格的简化版本。 我的查询是选择最后X个测试结果超过10的所有patientIds。结果应该只是患者ID 1和3.

此表中有超过30,000条记录。我无法找到更好的方法来完成这项工作。

PatientId   Test    Result  Date
1           X       11      2011/05/11
1           X        5      2005/05/11
1           Y        5      2011/05/11
2           X        5      2011/05/11
2           X       12      2005/05/11
2           Z       12      2011/05/11
3           X       16      2011/05/11
4           X       9       2005/05/11

3 个答案:

答案 0 :(得分:2)

我会做这样的事情:

SELECT a.PatientId
FROM
    some_table AS a
    INNER JOIN (
        SELECT PatientId, MAX(Date) AS Date
        FROM some_table
        WHERE Test = 'X'
        GROUP BY PatientId
    ) AS lr ON a.PatientId = lr.PatientId AND a.Date = lr.Date
WHERE a.Test = 'X' AND a.Result > 10

答案 1 :(得分:1)

如果我理解正确(使用您提供的数据,查询应该返回PatientId 2和3),这样的事情应该有效:

WITH TT (PatientId, Test, Result, N) AS (
    SELECT PatientId,
           Test,
           Result
           ROW_NUMBER() OVER(PARTITION BY PatientId ORDER BY Date ASC)
      FROM some_table
     WHERE Test = 'X')
    SELECT PatientId
      FROM TT
     WHERE Result > 10
       AND N = 1;

没有CTE:

SELECT PatientId
  FROM (SELECT PatientId,
               Test,
               Result
               ROW_NUMBER() OVER(PARTITION BY PatientId ORDER BY Date ASC) N
          FROM some_table
         WHERE Test = 'X') tmp
 WHERE Result > 10
   AND N = 1

答案 2 :(得分:1)

你可能会使用CTE,但我不知道它们,所以我会尝试传统的内部联接。免责声明: - 完全来自记忆,所以可能无法运行。

SELECT a.* 
FROM Tests a 
INNER JOIN (SELECT patient_id, test, max(date) as maxdate 
              FROM Tests 
             WHERE test = 'X' 
          GROUP BY patient_id, test) b
        ON a.patient_id = b.patient_id
       AND a.test = b.test
       AND a.date = b.maxdate
     WHERE a.result > 10

希望这会有所帮助。