简体   繁体   中英

SQL Query: Display only latest Id from each set

I have the following SQL Table:

Name       Description   Id   UserId   CreatedDate
UserSet1   Desc1         1    Abc      06/01/2018
UserSet1   Desc2         2    Def      06/02/2018
UserSet2   Desc for 2    5    NewUser  06/04/2018
UserSet2   Desc for 2    7    NewUser  06/19/2018

What I want to extract from the above table is just the latest Id for each Name so that I could get the following output

Name      Description    Id    UserId    CreatedDate
UserSet1  Desc2          2     Def       06/01/2018
UserSet2  Desc for 2     7     NewUser   06/19/2018

Since Id 2 & 7 are the latest entries in the table for UserSet1 & UserSet2, I would like to display that instead of all the entries in the table.

Any inputs how can I get the desired result.

I am open for solutions directly returning the output or any linq (C#) solutions as well. Ie returning the entire dataset and then using linq to filter the above.

EDIT: Since you are looking for the highest number ID, the GROUP BY method would probably be easier to work with.

Using a window function:

SELECT *
FROM (
    SELECT Name, Description, Id, UserId, CreatedDate
        , ROW_NUMBER() OVER (PARTITION BY Name ORDER BY CreatedDate DESC) AS rn
    FROM myTable
) s1
WHERE rn = 1

I don't have an instance of dynamoDB to test on, but I believe it can use the ROW_NUMBER() window function.

Thanks everyone for pointing to right direction. I have got this working with the below code of Linq and C#:

 var results = response.GroupBy(row => row.Name)
                   .SelectMany(g => g.OrderByDescending(row => row.Id).Take(1));

For the initial tests this seems to be working. Let me know if you think this has come issues.

This should be a general SQL answer:

SELECT * FROM yourtable Y1
WHERE Id = (SELECT MAX(Id)
              FROM yourtable Y2
             WHERE Y2.Name = Y1.Name)

If it was MS SQL you could use Partition By command, otherwise most performant way would be:

select * from Table
where Id in (
    select Max(Id) from Table
    Group By Name
)

not sure if you can leave Name out of the Select statement, you might need to do:

select * from Table
where Id in (
    Select Id from 
        (select Name, Max(Id) as Id from Table
        Group By Name)
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM