简体   繁体   中英

SQL Select Only Rows Where Certain Condition is met

This seems like a basic question but I just can't figure it out (Oracle SQL).

I need to pull the date of a patient visit for certain visit intervals which are contained in multiple tables, however one of these tables contains multiple visits:

Baseline table: Patient Number , Visit Date (This is the baseline visit)

Procedure table: Patient Number , Visit Date (This is the procedure visit)

Follow up table: Patient Number , Visit Interval , Visit Date (where Visit Interval contains values such as '1_month visit', '2_month visit', '3_month visit', etc.)

I want to put together a table of visit dates with each patient as a row and each visit interval as a column heading. I've tried to do this using CASE statements but I return multiple rows for a single patient.

This is what I have so far:

SELECT DISTINCT
    BASE.PT AS "Patient Number",
    BASE.VIST_DATE AS "Baseline",
    PROC.VISIT_DATE AS "Procedure",
    CASE
        WHEN FOLLOWUP.VISIT_INTERVAL = '1_Month'
        THEN FOLLOWUP.VISIT_DATE
        ELSE NULL END AS "1 Month",
    CASE
WHEN FOLLOWUP.VISIT_INTERVAL = '2_Month'
    THEN FOLLOWUP.VISIT_DATE
    ELSE NULL END AS "2 Month"
FROM BASE
LEFT JOIN PROC
    ON BASE.PT=PROC.PT
LEFT JOIN FOLLOWUP
    ON BASE.PT=FOLLOWUP.PT

This returns 2 rows per patient, with 1 row containing the Baseline, Procedure, and 1 Month visit dates (2 month column null) and the other row containing the Baseline, Procedure, and 2 Month visit dates (1 month column null). I want to display 1 row per patient with all dates populated. I'm obviously missing something (or going about it poorly in general) so I've posted for help.

Thank you!

You have two intervals for each patient, so you'll have two rows for each patient!

Your first row is the one with '1_month' interval, in this row you have only that column populated, and the same for the other row with '2_month' interval and measure.

For having the correct result you can use aggregates:

SELECT
    BASE.PT AS "Patient Number",
    MAX(BASE.VIST_DATE) AS "Baseline",
    MAX(PROC.VISIT_DATE) AS "Procedure",
    CASE
        WHEN FOLLOWUP.VISIT_INTERVAL = '1_Month'
        THEN FOLLOWUP.VISIT_DATE
        ELSE NULL END AS "1 Month",
    CASE
WHEN FOLLOWUP.VISIT_INTERVAL = '2_Month'
    THEN FOLLOWUP.VISIT_DATE
    ELSE NULL END AS "2 Month"
FROM BASE
LEFT JOIN PROC
    ON BASE.PT=PROC.PT
LEFT JOIN FOLLOWUP
    ON BASE.PT=FOLLOWUP.PT
GROUP BY BASE.PT

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM