Home >Database >Mysql Tutorial >How Can I Use DISTINCT and ORDER BY Together in a Single SQL SELECT Statement to Remove Duplicates and Sort by Date?
Using DISTINCT and ORDER BY in a Single SELECT Statement
In an attempt to remove duplicates from a result set while ordering the data by a specific date, you've encountered an issue where DISTINCT and ORDER BY don't seem to be working together as expected.
The challenge arises when the column used in the ORDER BY clause is not specified in the DISTINCT function. To address this, it's necessary to utilize an aggregate function within the DISTINCT and group the data by the desired category.
To achieve the desired result, consider the following code:
SELECT DISTINCT Category, MAX(CreationDate) FROM MonitoringJob GROUP BY Category ORDER BY MAX(CreationDate) DESC, Category
This query uses the aggregate function MAX(CreationDate) to sort the rows by their latest creation date. The GROUP BY clause ensures that only distinct categories are included in the result set. Finally, the ORDER BY clause is applied to the aggregate function and the category column, guaranteeing that the categories are ordered in the specified manner.
The above is the detailed content of How Can I Use DISTINCT and ORDER BY Together in a Single SQL SELECT Statement to Remove Duplicates and Sort by Date?. For more information, please follow other related articles on the PHP Chinese website!