具有多个连接和子查询的最新记录值

时间:2017-04-07 20:04:07

标签: sql sql-server

我正在使用MS SQL Server 2016.我尝试使用row_number函数获取最新的测量值,但仍然获得多个记录而不是最近的测量值。我有点超出我的SQL舒适区,非常感谢任何帮助。是否可以在子查询中使用row_number函数?

SELECT
    DISTINCT 
    V_PAT_FACT.PAT_ID,
    V_PAT_FACT.PAT_NAME, 
    CAST(PATIENT.BIRTH_DATE as date) "BIRTH DATE", 
    V_PAT_FACT.SEX_NAME as "GENDER", 
    V_PAT_FACT.CUR_PCP_NAME, 
    V_PAT_FACT.PAT_MRN_ID, 
    CAST(DATEADD(d,CAST(fmid7947.MEAS_VALUE as NUMERIC),'12/31/1840') as DATE) "RESTART DATE",
    CAST(DATEADD(d,CAST(fmid7948.MEAS_VALUE as NUMERIC),'12/31/1840') as DATE) "INITIAL DATE",
    FLOOR(CAST(LEFT(CAST(fmid7739.MEAS_VALUE as numeric), 4) AS numeric (8,3))/16) "INIT GOAL WT",
    FLOOR(CAST(LEFT(CAST(fmid7912.MEAS_VALUE as numeric), 4) AS numeric (8,3))/16) "INIT RESTART WT",
    fmid8794.MEAS_VALUE "TGT MAINT WT",
    FLOOR(CAST(fmid14.MEAS_VALUE as numeric(8,3))/16) "WT LBS",
    fmidBMI.MEAS_VALUE as "BMI",
    FLOOR(CAST(LEFT(CAST(fmid8796.FSD_ID as numeric), 4) AS numeric (8,3))/16)"TOTAL LOSS",
    fmid7752.MEAS_VALUE as "BARIATRIC MED"

FROM
    V_PAT_FACT V_PAT_FACT
    LEFT  OUTER JOIN PATIENT        ON V_PAT_FACT.PAT_ID = PATIENT.PAT_ID
    INNER JOIN       IP_FLWSHT_REC  ON V_PAT_FACT.PAT_ID = IP_FLWSHT_REC.PAT_ID 
    INNER JOIN       IP_FLWSHT_MEAS ON
        IP_FLWSHT_REC.FSD_ID = IP_FLWSHT_MEAS.FSD_ID 
        AND
        IP_FLWSHT_MEAS.FLT_ID = '343'
        AND
        IP_FLWSHT_MEAS.FLO_MEAS_ID IN ( '7947', '7948', '7739', '7912', '8794', '8481', '14', '301070', '8796','7752' )
    INNER JOIN       IP_FLO_GP_DATA ON IP_FLWSHT_MEAS.FLO_MEAS_ID = IP_FLO_GP_DATA.FLO_MEAS_ID
    LEFT OUTER JOIN
    (
        SELECT
            DISTINCT
            mes.FLO_MEAS_ID,
            mes.MEAS_VALUE,
            vp.PAT_ID,
            rsdate.MEAS_VALUE AS "something"
        FROM
            PAT_ENC vp
            INNER JOIN IP_FLWSHT_REC rec on vp.PAT_ID=rec.PAT_ID
            INNER JOIN IP_FLWSHT_MEAS mes on rec.FSD_ID=mes.FSD_ID
            INNER JOIN (
                SELECT
                    m.*,
                    row_number() over (partition by FSD_ID  Order by ENTRY_TIME desc) as rn
                FROM
                    IP_FLWSHT_MEAS m
                WHERE
                    M.FLO_MEAS_ID = '7948'
            ) rsdate ON mes.FSD_ID = rsdate.FSD_ID
        WHERE
            mes.FLO_MEAS_ID ='7948'
    ) fmid7948 ON V_PAT_FACT.PAT_ID = fmid7948.PAT_ID

0 个答案:

没有答案