I have a table with two DateTime columns, _dateEntry and _dateUpdate.
I've to create a query and choose the right datetime column based on these conditions: take the most recent between _dateEntry and _dateUpdate. _dateUpdate might be null, so I wrote this condition
SELECT id, description, ISNULL(_dateUpdate, _dateEntry) as date FROM mytable
but is not enought as I've to get also the most recent. How can I modify my query?
You can use a case to return what you want:
SELECT
id
, description
, CASE WHEN _dateEntry > ISNULL(_dateUpdate,0)
THEN _dateEntry ELSE _dateUpdate END AS date
FROM
mytable
I suppose _dateEntry is never NULL. If can be NULL tell me because I change my query
Try this:
SELECT id, description,
CASE
WHEN _dateUpdate IS NULL THEN _dateEntry
WHEN _dateUpdate > _dateEntry THEN dateUpdate
ELSE _dateEntry
END as date
FROM mytable
ORDER BY
CASE
WHEN _dateUpdate IS NULL THEN _dateEntry
WHEN _dateUpdate > _dateEntry THEN dateUpdate
ELSE _dateEntry
END desc
So if _dateUpdate IS NULL you'll get the value of _dateEntry, so the order is on two fields
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