I use SQL Server 2008 R2
.
I need to sort a table by the minimal value of two columns.
The table looks like this:
ID: integer; Date1: datetime; Date2: datetime.
I want my data to be sorted by minimal of two dates.
What is the simplest way to sort this table that way?
We can use a nested CASE statement to compare the values of multiple columns to get the minimum value. Also, we can use the nested IIF statement. The query should look like this.
If you want to select records from a table but would like to see them sorted according to two columns, you can do so with ORDER BY . This clause comes at the end of your SQL query.
If you are trying to get the row-wise mininum of two or more columns, use pandas. DataFrame. min . Note that by default axis=0 ; specifying axis=1 is necessary.
NOT NULL columns. You need to add CASE expression into ORDER BY clause in following:
SELECT Id, Date1, Date2 FROM YourTable ORDER BY CASE WHEN Date1 < Date2 THEN Date1 ELSE Date2 END
NULLABLE columns. As Zohar Peled wrote in comments if columns are nullable you could use ISNULL
(but better to use COALESCE
instead of ISNULL
, because It's ANSI SQL standard
) in following:
SELECT Id, Date1, Date2 FROM YourTable ORDER BY CASE WHEN COALESCE(Date1, '1753-01-01') < COALESCE(Date2, '1753-01-01') THEN Date1 ELSE Date2 END
You can read about ANSI standard dateformat 1753-01-01
here.
Use a CASE
expression in the ORDER BY
:
ORDER BY case when date1 < date2 then date1 else date2 end
Edit:
If null values need to be considered, add coalesce()
:
ORDER BY case when date1 < date2 then date1 else coalesce(date2,date1) end
Explanation:
If date1 < date2 then order by date1. (Both dates are non null here.) Works just like before.
Else use COALESCE()
to order by date2 (when date2 is not null), or date1 (when date2 is null), or by null (if both dates are null.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With