Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Group with Order by

Tags:

sql

sql-server

This feels like it should have a basic solution but I don't seem to be getting it.

Take this query:

            SELECT Category FROM Article
            GROUP BY Category

I want to effectively do this:

            SELECT Category, DatePublished FROM Article 
            GROUP BY Category
            ORDER BY DatePublished DESC

I don't really want to select DatePublished, but it seemed to make sense to order by it. That doesn't work though.

Basically I want to order categories by the most recent DatePublished article.

like image 383
Chris James Avatar asked Nov 10 '09 15:11

Chris James


1 Answers

SELECT  Category
FROM    Article
GROUP BY
        Category
ORDER BY
        MAX(DatePublished) DESC

Since you do a GROUP BY, you need to run some aggregate function over non-grouping columns.

MAX will select the date of last published article from each category and order categories accordingly.

like image 106
Quassnoi Avatar answered Sep 21 '22 21:09

Quassnoi