SQL 基于多个日期列创建最小日期列的代码
SQL code to create min date column based on multiple date columns
我有一个包含多个日期列的 SQL table,其中一些是空白的 (Example of Table) and I want to create a column in SQL that calculates the earliest date across the 3 columns (Expected Output)
任何帮助将不胜感激!
请始终提及带有版本的数据库名称以获得更好的解决方案。
架构和插入语句:
create table Patients (Patient varchar(50), Doctor_Date date, Nurse_Date date, Physio_Date date);
insert into Patients (Patient,Doctor_Date)values ('Patient 1','26/11/2021');
insert into Patients (Patient,Doctor_Date,Nurse_Date,Physio_Date) values('Patient 2','17/11/2021','20/11/2021','16/11/2021');
insert into Patients (Patient,Nurse_Date,Physio_Date) values('Patient 3','5/12/2021','4/05/2021');
查询:
select Patient,
(SELECT MIN(mindate) FROM (VALUES (Doctor_Date), (Nurse_Date), (Physio_Date)) AS X(mindate)) AS Minimum_Date
from Patients
输出:
patient
minimum_date
Patient 1
2021-11-26
Patient 2
2021-11-16
Patient 3
2021-05-04
db<>fiddle here
我有一个包含多个日期列的 SQL table,其中一些是空白的 (Example of Table) and I want to create a column in SQL that calculates the earliest date across the 3 columns (Expected Output)
任何帮助将不胜感激!
请始终提及带有版本的数据库名称以获得更好的解决方案。
架构和插入语句:
create table Patients (Patient varchar(50), Doctor_Date date, Nurse_Date date, Physio_Date date);
insert into Patients (Patient,Doctor_Date)values ('Patient 1','26/11/2021');
insert into Patients (Patient,Doctor_Date,Nurse_Date,Physio_Date) values('Patient 2','17/11/2021','20/11/2021','16/11/2021');
insert into Patients (Patient,Nurse_Date,Physio_Date) values('Patient 3','5/12/2021','4/05/2021');
查询:
select Patient,
(SELECT MIN(mindate) FROM (VALUES (Doctor_Date), (Nurse_Date), (Physio_Date)) AS X(mindate)) AS Minimum_Date
from Patients
输出:
patient | minimum_date |
---|---|
Patient 1 | 2021-11-26 |
Patient 2 | 2021-11-16 |
Patient 3 | 2021-05-04 |
db<>fiddle here