Mr A
Mr A

Reputation: 6778

Sql Query Sorting Issues

I have got 2 fields in my db(sql server 2008) namely updateDate[Datetime] & calldate[datetime]. The sql query I am running to get the data from th db is :

Select * from [Clients] where [Timestamp] < GetDate() ORDER BY calldate, updateDate

Now the issue is the callbackdate has default value of minimum date , so if no date is passed , it adds the minimumdate, I want to add a check on the above query so it doesnt sort the records with calldate value is set to minimum date value. For instance if the calldate is minimumdate then that record should be sorted by renewal date.Is it possible to acheive something like this.

Any suggestions or advice will be highly appreciated. Thanks

Upvotes: 0

Views: 112

Answers (3)

Lamak
Lamak

Reputation: 70668

DECLARE @minimumdate DATETIME

SELECT @minimumdate = MIN(calldate) FROM [Clients]

Select * 
from [Clients] 
where [Timestamp] < GetDate() 
ORDER BY CASE WHEN calldate = @minimumdate THEN updateDate ELSE calldate END

Upvotes: 1

silly
silly

Reputation: 7887

try this (if minimunm date is 2009-01-01)

ORDER BY (CASE WHEN CallDate=DATE('2009-01-01') THEN RenewDate else CallDate END)

Upvotes: 1

Michael Fredrickson
Michael Fredrickson

Reputation: 37398

Select YourColumns
from [Clients] 
where [Timestamp] < GetDate() 
order by 
    case when callDate = minimumDate then updateDate else callDate end, 
    updateDate

Upvotes: 1

Related Questions