简体   繁体   English

根据 SQL 中的条件创建另一列

[英]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例如,Shahin Adam 只需要 1 个单独的记录,将剂量 1 和剂量 2 的详细信息与每个剂量的日期结合起来

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.根据所需的输出结果部分,只显示 2 个名字以 A 开头的记录。这就是这里启用 where 子句的原因。 If all patients info need then disable where clause.如果所有患者信息都需要,则禁用 where 子句。

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;

 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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