HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlMinor

Order By DateTime With 00:00:00 Last

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
withlastorderdatetime

Problem

order by datetimecolumn orders a datetime column like this:

datetimecolumn   
2014-09-04 00:00:00
2014-09-04 00:00:00
2014-09-04 01:00:00
2014-09-05 00:00:00
2014-09-05 01:00:00
2014-09-05 02:00:00


How can I order the data so the the values with 00:00:00 are last, but still order the values ascending by time like so:

datetimecolumn    
2014-09-04 01:00:00
2014-09-04 00:00:00
2014-09-04 00:00:00
2014-09-05 01:00:00
2014-09-05 02:00:00
2014-09-05 00:00:00


Dumb business rule, I know I know... basically if "user" does not spec a time, the time does not matter (so it goes to the bottom of the list).

Solution

First order by just the date, then prioritize the values where the timestamp is not midnight over those where it is.

ORDER BY CONVERT(DATE, col),
  CASE WHEN CONVERT(DATE,col) = col     
  THEN 2 ELSE 1 END,
  CONVERT(TIME, col);

Code Snippets

ORDER BY CONVERT(DATE, col),
  CASE WHEN CONVERT(DATE,col) = col     
  THEN 2 ELSE 1 END,
  CONVERT(TIME, col);

Context

StackExchange Database Administrators Q#121370, answer score: 7

Revisions (0)

No revisions yet.