2

I have a table WebOrder
Below is a simplified version of the table (I omitted most of the columns that weren't necessary for this post)

+-------------------+----------------+
|Field              |Type            |
+-------------------+----------------+
|WebOrderID         |Int             |
|DueDate            |Date            |
|Customer           |nvarchar(50)    |
+-------------------+----------------+

I would like to sort by due date which is easy enough with

SELECT * FROM WebOrder ORDER BY DueDate

However I would like to take that sorting a step further and have WebOrders that are due on the current date to display at the top, followed WebOrders that are due at a later date, and finally have the later due dates followed by past due dates.
Below is an example of what the output would look like

+-------------------+----------------+-----------------+
|WebOrderID         |DueDate         |Customer         |
+-------------------+----------------+-----------------+
|23                 |2020-06-24      |Phillip Fry      |
|2                  |2020-06-24      |Karen Clay       |
|35                 |2020-06-26      |George Sun       |
|64                 |2020-06-28      |Austin Powers    |
|1                  |2020-06-01      |Wu Lang          |
|12                 |2020-06-05      |Jessica Myers    |
|6                  |2020-06-07      |Sarah Red        |
+-------------------+----------------+-----------------+

This post was very similar to what I wanted to achieve, Sorting data according to current date, however I wasn't sure how to achieve the same thing in sql server. This is my first post so let me know how I can improve my question and post.

GMB
  • 216,147
  • 25
  • 84
  • 135
Chase T
  • 47
  • 5

1 Answers1

1

Consider a conditional sort:

order by
    case 
        when dueDate = cast(getdate() as date) then 0
        when dueDate > cast(getdate() as date) then 1
        else 2
    end,
    dueDate

The first expression in the order by clause gives priority to record on the current date, then to future records. The second sorting criteria sorts then subsets by dueDate.

GMB
  • 216,147
  • 25
  • 84
  • 135