【问题标题】:Get the earliest of a date-value pair in T-SQL获取 T-SQL 中最早的日期值对
【发布时间】:2021-03-19 07:16:21
【问题描述】:
我正在尝试在 t-sql 中构建查询以添加自定义日期值对列。我的数据包含项目 ID、L 日期和 L 状态、N 日期和 N 状态。我知道如何使用 min 函数添加最早的日期。如何在我的新列中捕获最早日期及其对应状态?在下面的示例中,我需要找到最早的一对。我假设的查询应该根据 N 和 L 日期值对中的数据将结果带入 Earliest Dt 和 Status。
【问题讨论】:
标签:
sql-server
tsql
datetime
unpivot
lateral-join
【解决方案1】:
您可以通过横向连接来做到这一点。这个想法是将列取消旋转到列,然后排序:
select t.*, x.*
from mytable t
cross apply (
select top (1) x.*
from (values (t.l_date, t.l_status), (t.n_date, t.n_status)) x(earlierst_dt, status)
order by x.earlierst_dt desc
) x
这是因为 SQL Server 在降序排序时将 null 值放在最后。
您也可以使用case 表达式,但输入逻辑有点麻烦:
select t.*,
case when l_date > n_date or (l_date is not null and n_date is null) then l_date else n_date end as earlierst_date,
case when l_date > n_date or (l_date is not null and n_date is null) then l_status else n_status end as status
from mytable t