SQL Server: How to order by date, if the date is < GetDate()
-
10-07-2019 - |
Question
Here's an interesting one... hope I can explain it well...
I have a collection of competitions in a single table in my SQL Server DB. I'm doing a full text search over them, which works fine. However, some of the competitions are closed, and I want these closed comps to show up after the open comps, while still respecting the rank we get from full text search.
So if I had an IsOpen bit feild, I would them ordered by
ORDER BY IsOpen DESC, KEY_TBL.Rank DESC
Now the problem is I don't have an IsOpen bit field. Instead, I have a ClosedDate field, which is a datetime.
So What I really need to do is something like:
ORDER BY (ClosingDate < GetDate()) ASC, KEY_TBL.Rank DESC
Anyone know how to do this?
Any ideas would be great! Thanks in advance.
-Ev
Solution
ORDER BY
CASE
WHEN (ClosingDate < GetDate())
THEN 1
ELSE 0
END ASC,
KEY_TBL.Rank DESC
OTHER TIPS
add (ClosingDate < GetDate()) to the SELECTed fields and order by that field
select ... , add (ClosingDate < GetDate()) as Foo
from ...
where ...
order by foo
possibly add (ClosingDate < GetDate()) will not be accepted, then you will have to use IF(add (ClosingDate < GetDate());1;0)
I don't know the syntax of that IF function by heart, look it up!