Extended Sort Key Columns
The reason you don't want to work is because of the logical order of operations in SQL , which for your first query (simplified):
FROM MonitoringJobSELECT Category, CreationDate i.e. add the so-called extended sort key columnORDER BY CreationDate DESCSELECT Category i.e. remove the extended collation key column from the result again.
Thus, thanks to the standard function of the extended column of the SQL collation key, you can completely order something that is not in the SELECT because it is temporarily added to it behind the scenes.
So why does this not work with DISTINCT ?
If we add a DISTINCT operation, it will be added between SELECT and ORDER BY :
FROM MonitoringJobSELECT Category, CreationDateDISTINCTORDER BY CreationDate DESCSELECT Category
But now, with the CreationDate extended collation key column, the semantics of the DISTINCT operation have been changed, so the result will no longer be the same. This is not what we want, so the SQL standard and all reasonable databases prohibit this use.
workarounds
It can be emulated with standard syntax as follows
SELECT Category FROM ( SELECT Category, MAX(CreationDate) AS CreationDate FROM MonitoringJob GROUP BY Category ) t ORDER BY CreationDate DESC
Or just (in this case) as shown by Prutswonder
SELECT Category, MAX(CreationDate) AS CreationDate FROM MonitoringJob GROUP BY Category ORDER BY CreationDate DESC
I wrote more about SQL DISTINCT and ORDER BY here .
Lukas Eder Jul 20 '18 at 8:24 2018-07-20 08:24
source share