从 Johann 那里得到了排序方法
Select Top 1
*
From (
Select
0 As X,
*
From
Encounter
Where
-- started after 00:00:00 today (maybe Started > GetDate() will suffice)
Started >= DateAdd(day, DateDiff(day, 0, GetDate()), 0) And
-- started before 00:00:00 tomorrow
Started < DateAdd(day, 1 + DateDiff(day, 0, GetDate()), 0)
Union All
Select
1 As X,
*
From
Encounter
Where
-- Sechduled after 00:00:00 today
Scheduled >= DateAdd(day, DateDiff(day, 0, GetDate()), 0) And
-- started before 00:00:00 tomorrow
Scheduled < DateAdd(day, 1 + DateDiff(day, 0, GetDate()), 0)
) a
Order By
X,
Started Desc,
Scheduled Asc
假设开始总是与预定的同一天,并且预定不能为空,这相当于:
Select Top 1
*
From
Encounter
Where
-- Sechduled after 00:00:00 today
Scheduled >= DateAdd(day, DateDiff(day, 0, GetDate()), 0) And
-- started before 00:00:00 tomorrow
Scheduled < DateAdd(day, 1 + DateDiff(day, 0, GetDate()), 0)
Order By
Case When Started Is Null Then 0 Else 1 End,
Started Desc,
Scheduled;
http://sqlfiddle.com/#!3/9cc65/3