简体   繁体   中英

How to select distinct result set in SQL Server?

I have a table, sample data like this. There are names associated with multiple ids

Id Name
-------
1 A
1 B
2 A
2 B

Result needed

ID Name
--------
1 A
1 B

How to get this? Order of ID doesn't matter

TL; DR

SELECT min(id) as id, name from mytable GROUP BY name

When you need to summarize over multiple records in SQL, each column you include should either be aggregated using a function like min(), max() or sum(); or included in the GROUP BY clause. Here you are looking to pick an arbitrary ID, so why not use the "min()" ID? Then we want each unique name, so we add it to the GROUP BY clause.

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