简体   繁体   中英

Grouping results in sql query by a field in the result

I have a table with the following format:

User | Entity | ID
123    AB       1
123    AB       2
543    BC       3
098    CB       4
543    BC       5
543    ZG       6

etc...

I want to get a result set that only returns the User/Entity pairs and their ID for the greatest ID, so this result for example:

User | Entity | ID
123    AB        2
098    CB        4
543    BC        5
543    ZG        6

Is there any way to do this in SQL?

Try to use group by with max function

select user, Entity, max(id) as id
from table 
group by user, Entity

You can also use CTE and Partition By

Like this:

;WITH CTE as
(
SELECT
    Users,Entity,
    ROW_NUMBER() OVER(PARTITION BY Entity ORDER BY ID DESC) AS Row,
    Id
    FROM Item
)
SELECT Users, Entity, Id From CTE Where Row = 1

Note that we used Order By ID DESC as we need highest ID . You can delete DESC if you want the smallest ID .

SQLFiddle: http://sqlfiddle.com/#!3/1dcb9/4

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