如何使用三个可用的最小日期 - SQL

时间:2015-02-17 14:00:07

标签: sql sql-server

我正在尝试将一个公式插入一个查询中,以便取回应该在特定合同上运行多少。

公式本身很简单,但我无法在任何地方找到如何根据每条记录单独取3之间的最小日期。

我需要计算每个合约中最早的Term_dateSuspend_date今天的日期,其中一些可能是NULL。< / p>

4 个答案:

答案 0 :(得分:3)

有趣的方法是使用cross apply

select t.contractid, mindte
from table t cross apply
     (select min(dte) as mindte
      from (values(t.term_date), (t.suspend_date), (getdate())) d(dte)
     ) d;

答案 1 :(得分:2)

CASE 
    WHEN Term_date < Suspend_date AND Term_date < GETDATE() THEN Term_date
    WHEN Suspend_date < GETDATE() THEN Suspend_date
    ELSE GETDATE()
END AS MinimumDate

答案 2 :(得分:0)

我知道会提出CASE声明,但我想我会尝试不同的事情:

;WITH cte (RecordID, CheckDate) AS
( SELECT RecordID, Term_date FROM sourcetable UNION ALL
  SELECT RecordID, Suspend_date FROM sourcetable UNION ALL
  SELECT RecordID, GETDATE() FROM sourcetable )
SELECT src.RecordID, src.Field1, src.Field2, MinDate = MIN(cte.CheckDate)
FROM sourcetable src
LEFT JOIN cte ON cte.RecordID = src.RecordID
GROUP BY src.RecordID, src.Field1, src.Field2

答案 3 :(得分:0)

以下是使用cross apply生成工作表的方法,您可以从中获取最短日期:

-- mock table with sample testing data
declare @MyTable table
(
    id int identity(1,1) primary key clustered,
    term_date datetime null,
    suspend_date datetime null
)
insert into @MyTable (term_date, suspend_date)
select null, null
union all select '1/1/2015', null
union all select null, '1/2/2015'
union all select '1/3/2015', '1/3/2015'
union all select '1/4/2015', '1/5/2015'
union all select '1/6/2015', '1/5/2015'

select * from @MyTable

select datevalues.id, min([date])
from @MyTable
cross apply
(
    values (id, term_date), (id, suspend_date), (id, getdate())
) datevalues(id, [date])
group by datevalues.id