How to use top 1 with group by

Y.N 80 Reputation points
2024-01-30T03:30:20.0233333+00:00

Need to query latest record of each ID. Tried Max, but it seems not possible to have col2 in output. Also, the top 1 function not worked here. Here is the demo table:

create table #demo (ID INT,col1 DATETIME,col2 INT)

INSERT INTO #demo SELECT 1, '2024-01-29', 100
INSERT INTO #demo SELECT 1, '2024-01-28', 123
INSERT INTO #demo SELECT 1, '2024-01-27', 154
INSERT INTO #demo SELECT 2, '2024-01-29', 178
INSERT INTO #demo SELECT 2, '2024-01-28', 200
INSERT INTO #demo SELECT 2, '2024-01-25', 90
SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
14,492 questions
0 comments No comments
{count} votes

Accepted answer
  1. LiHongMSFT-4306 31,311 Reputation points
    2024-01-30T03:42:59.03+00:00

    Hi @Y.N If I understand right, you could use Row_number here.

    Check this:

    SELECT ID,col1,col2
    FROM (SELECT *,ROW_NUMBER()OVER(PARTITION BY ID ORDER BY col1 DESC)AS RNum FROM #demo)S
    WHERE S.RNum=1
    

    Best regards, Cosmog Hong


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.