SQL - 在整数列和特定日期

时间:2015-10-05 19:56:17

标签: sql-server sql-server-2008 max

我正在处理一个报表查询,其中我只需要使用日期范围的最新行,以及patientid和Type_Name。 int列'ednum'在任何特定日期都可以有很多行,我只需要在日期范围内为该患者提供最高ednum的行。

我正在使用单个表试图向下钻取以显示每个日期的一个ednum值(ednum值为MAX)这是我的尝试,它运行但没有给出MAX(ednum)值,但包含相同的其他行日期。

MS SQL 2008

SELECT TP2.ednum, TP2.BackgroundID, TP2.Patient_No, TP2.Last_Name, TP2.Visit_Name, 
TP2.SessionDT
FROM  dbo.TypePatient AS TP1 INNER JOIN
      (SELECT ednum, BackgroundID, CONVERT(varchar,  DATE_, 101) AS SessionDT, Patient_No, Last_Name, Visit_Name
              FROM          dbo.TypePatient
              WHERE      (Visit_Name = 'Progress Note')) AS TP2  ON TP1.BackgroundID = TP2.BackgroundID AND TP1.ednum =
              (SELECT     TOP (100) PERCENT MAX(ednum) AS ednum
              FROM          dbo.TypePatient
              WHERE      (BackgroundID = 3304) AND (TP2.SessionDT
BETWEEN '09/20/2015' AND '09/26/2015') AND (Visit_Name = 'Progress Note')
ORDER BY TP2.SessionDT)
GROUP BY TP2.SessionDT, TP2.ednum, TP2.BackgroundID, TP2.Patient_No, TP2.Last_Name, TP2.Visit_Name, TP2.ednum

MS SQL 2008

1 个答案:

答案 0 :(得分:0)

WITH X AS 
(
    SELECT ednum
         , BackgroundID
         , Patient_No
         , Last_Name
         , Visit_Name
         , SessionDT
         , ROW_NUMBER () OVER (PARTITION BY Patient_No ORDER BY ednum DESC) rn 
    FROM  dbo.TypePatient 
    WHERE Visit_Name = 'Progress Note'
     AND SessionDT BETWEEN '20150920' AND '20150926'
)
SELECT * FROM X 
WHERE rn = 1