我在MS SQL Server Management Studio中工作。我创建了一个键入patientId的视图,每个患者/行有12个相关日期。在SQL中是否有一种方法可以找到每行的最小和最大日期? 任何帮助将不胜感激。
答案 0 :(得分:4)
您可以使用“unpivot”。请查看以下示例:
CREATE TABLE dates
(
number INT PRIMARY KEY ,
date1 DATETIME ,
date2 DATETIME ,
date3 DATETIME
)
INSERT INTO dates
VALUES ( 1, '1/1/2018', '2/4/2018', '3/1/2018')
INSERT INTO dates
VALUES ( 2, '1/2/2018', '2/3/2018', '3/3/2018')
INSERT INTO dates
VALUES ( 3, '1/3/2018', '2/2/2018', '3/2/2018')
INSERT INTO dates
VALUES ( 4, '1/4/2018', '2/1/2018', '3/4/2018')
GO
SELECT number ,
MIN(dDate) mindate,
MAX(dDate) maxDate
FROM dates UNPIVOT ( dDate FOR nDate IN ( Date1, Date2,Date3 ) ) as u
GROUP BY number
GO
答案 1 :(得分:2)
我会使用cross apply
执行此操作:
select t.*, v.mind, v.maxd
from t cross apply
(select min(v.d) as mind, max(v.d) as maxd
from (values (d1), (d2), (d3), (d4), (d5), (d6), (d7), (d8), (d9), (d10), (d11), (d12)
) v(d)
) v;
请注意min()
和max()
忽略NULL
值。
答案 2 :(得分:1)
另一种方式:
create table MyDates
(
ID int,
D1 datetime,
D2 datetime,
D3 datetime
)
insert MyDates(ID, D1, D2, D3)
values (1, '19000101', '19720506', '20060204'),
(2, '20170624', '20180821', '20180901'),
(3, '19820202', '19840721', '19851231')
select *,
(select min(v) from (values(D1), (D2), (D3)) t(v)) [Min],
(select max(v) from (values(D1), (D2), (D3)) t(v)) [Max]
from MyDates