views:

102

answers:

2

Hi,

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

+2  A: 

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!

lexu
`CASE` is a better choice, but your algorithm is otherwise sound.
OMG Ponies
I'd just come to the same conclusion .. is there a select if(..) in TSQL? CASE is more flexible, since it is extensible to other conditions..
lexu
Thanks for the answer, it's the right idea that I was going for - a good steer in the right direction, but the syntax wasn't right - I couldn't get either the ADD or the IF() workign, but I found the CASE and it worked well. Thanks.
Ev
+2  A: 
ORDER BY
  CASE
    WHEN (ClosingDate < GetDate())
    THEN 1
    ELSE 0
  END ASC,
  KEY_TBL.Rank DESC
David B
@DavidB - thanks a lot for that. It worked a treat. However, I'll mention here, that once I'd implemented your suggestion I realised I could get the same result by simply ordering by the ClosedDate! Haha, but yeah, this is what I asked - thanks for the quick answer! :)
Ev