简体   繁体   中英

Create another column based on the conditions in SQL

I need help to create a query for this output below. As you can see in the below dataset, I wanted to have the patient record in a single row with all the details

数据集

For example, Shahin Adam need to have only 1 single record combine the details of Dose Number 1 and Dose Number 2 with the date of each dose

DESIRED OUTPUT

期望的输出

Thank you for your help

I think you just want conditional aggregation:

select lastname, firstname,
       max(case when dosenumber = 1 then dosenumber end) as dosenumber_1,
       max(case when dosenumber = 1 then timeofevent end) as timeofevent_1,
       max(case when dosenumber = 2 then dosenumber end) as dosenumber_2,
       max(case when dosenumber = 2 then timeofevent end) as timeofevent_2
from t
group by lastname, firstname;

As per desired output result section show only 2 records whose first name starts with A. That's why where clause is enabled here. If all patients info need then disable where clause.

SELECT PatientLastName, PatientFirstName
     , MAX(CASE WHEN DoseNumber = 1 THEN DoseNumber ELSE NULL END) DoseNumber1
     , MAX(CASE WHEN DoseNumber = 1 THEN TimeOfEvent ELSE NULL END) TimeOfEvent1
     , MAX(CASE WHEN DoseNumber = 2 THEN DoseNumber ELSE NULL END) DoseNumber2
     , MAX(CASE WHEN DoseNumber = 2 THEN TimeOfEvent ELSE NULL END) TimeOfEvent2
FROM table_name
WHERE PatientFirstName like 'A%'
GROUP BY PatientLastName, PatientFirstName
ORDER BY PatientFirstName;

 

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