Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL - Order by Max() on Alias

I gather that I cannot get the MAX() on some alias that I have in the select statement in sql queries?

Example:

Select  
    CASE WHEN CompletionDate IS NOT NULL THEN DATEDIFF(d, CreatedDate, CompletionDate) ELSE NULL END AS DaysLong
from CombinedMastervw 
WHERE CreatedDate Between '03/01/2019 23:59:59.991' AND '04/01/2019 23:59:59.991'
ORDER BY MAX(dayslong)

Thus my question is on MAX(dayslong), do I have to end up doing a Max with the same code in the SELECT statement?


1 Answers

You should be able to use the alias.

Try:

ORDER BY dayslong

Max(dayslong) would return the single maximum value in the table you are selecting, so you cannot order by it.

like image 168
Thomas Boeck Avatar answered Mar 16 '26 10:03

Thomas Boeck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!