选择最近的活动

时间:2017-01-26 07:58:12

标签: sql oracle greatest-n-per-group

我试图在手术前和手术后获得患者的最新实验室结果;我们想得到他的血红蛋白......

Lab table会显示他的实验室结果 Problem_list_cn会显示他的sugery

/ 此示例仅适用于之前的 /

SELECT L.RESULT_DE 
FROM LAB L INNER JOIN PROBLEM_LIST_CN PL
ON L.PATID_CD = PL.PAT_ID 
WHERE L.PROCEDURE_DE = 'HEMOGLOBIN' 
AND L.COLLECTION_DT = (SELECT (MAX L.COLLECTION_DT) FROM LAB L2 WHERE L2.COLLECTION_DT < PL.NOTED_DATE) As HEMOG_BEFORE;

enter image description here

2 个答案:

答案 0 :(得分:0)

假设字段LAB.PATID_CD包含患者的id,您应该按如下方式更改查询(即加入PATID_CD上的子查询)。我在MAX函数parenthesys上添加了一个小的修正。

   SELECT L.RESULT_DE 
   FROM LAB L INNER JOIN PROBLEM_LIST_CN PL
    ON L.PATID_CD = PL.PAT_ID 
   WHERE L.PROCEDURE_DE = 'HEMOGLOBIN' 
   AND L.COLLECTION_DT = (SELECT (MAX (L.COLLECTION_DT) FROM LAB L2 WHERE L2.COLLECTION_DT < PL.NOTED_DATE AND L2.PATID_CD=l.PATID_CD) As HEMOG_BEFORE;

答案 1 :(得分:0)

没有任何样本数据,很难测试,但是这样的话:

SELECT L.PATID_CD,
       MAX( L.RESULT_DE )
         KEEP ( DENSE_RANK LAST ORDER BY CASE WHEN L.COLLECTION_DT < PL.NOTED_DATE
                                              THEN L.COLLECTION_DT END NULLS FIRST )
         AS HEMOG_BEFORE,
       MAX( CASE WHEN L.COLLECTION_DT < PL.NOTED_DATE THEN L.COLLECTION_DT END )
         AS DATE_TAKEN_BEFORE,
       MAX( L.RESULT_DE )
         KEEP ( DENSE_RANK FIRST ORDER BY CASE WHEN L.COLLECTION_DT >= PL.NOTED_DATE
                                               THEN L.COLLECTION_DT END NULLS LAST)
         AS HEMOG_AFTER,
       MIN( CASE WHEN L.COLLECTION_DT >= PL.NOTED_DATE THEN L.COLLECTION_DT END )
         AS DATE_TAKEN_AFTER
FROM   LAB L
       INNER JOIN PROBLEM_LIST_CN PL
       ON ( L.PATID_CD = PL.PAT_ID )
WHERE L.PROCEDURE_DE = 'HEMOGLOBIN'
GROUP BY L.PATID_CD;

或:

SELECT *
FROM   (
  SELECT t.*,
         ROW_NUMBER() OVER ( PARTITION BY platin_cd ORDER BY date_after ) AS rid
  FROM   (
    SELECT l.platin_cd,
           LAG( l.result_de     ) OVER ( PARTITION BY l.platin_cd
                                         ORDER BY collection_dt ) AS hemog_before,
           LAG( l.collection_dt ) OVER ( PARTITION BY l.platin_cd
                                         ORDER BY collection_dt ) AS date_before,
           l.result_de AS hemog_after,
           l.collection_dt AS date_after,
           pl.noted_date
    FROM   LAB L
           INNER JOIN PROBLEM_LIST_CN PL
           ON ( L.PATID_CD = PL.PAT_ID )
    WHERE L.PROCEDURE_DE = 'HEMOGLOBIN'
  )
  WHERE  date_after >= noted_date
)
WHERE  rid = 1;