Search code examples
sql-serverdategroup-bymaxdate

SQL Server: get newest (most current) date per group


I have an SQL table with a column categoryX that contains dates (format: yyyy-mm-dd). How can i group the table by categories in this column and get the newest (most recent) date for each group ?

I am looking for something similar to the below which only counts the categories for each group - just instead of the count I would like to get the newest date for each group.

Here are the details on the table and column:

ALTER PROCEDURE [dbo].[CountRequests]
AS
BEGIN
    SET NOCOUNT ON;
    SELECT      categoryX,
                COUNT(*) AS categoryCount
    FROM        LogRequests
    WHERE       logStatus = 'active'
    AND         statusSOP != 'Published'
    GROUP BY    categoryX
    ORDER BY    categoryCount desc, categoryX
    FOR XML PATH('categoryX'), ELEMENTS, TYPE, ROOT('ranks')
END

Many thanks for any help with this


Solution

  • Your query will be something similar to

    SELECT      categoryX,
                MAX(CategoryDate) AS LatestDate
    FROM        YourTable
    GROUP BY    categoryX