我想总是只选择ID2中的最小数字和ID1
分组表:
| ID1 | ID2 | Name | Phone |
| 1 | 1 | Max | 123 |
| 1 | 2 | Ben | 254 |
| 1 | 3 | Robert | 541 |
| 2 | 1 | Andy | 515 |
| 2 | 2 | Carl | 631 |
这是我想要的输出:
| ID1 | Name | Phone |
| 1 | Max | 123 |
| 2 | Andy | 515 |
任何人都可以帮助我正确查询microsoft sql server吗??
答案 0 :(得分:3)
您可以使用CTE和排名函数,例如ROW_NUMBER
:
WITH CTE AS
(
SELECT ID1, ID2, Name, Phone,
RN = ROW_NUMBER() OVER (PARTITION BY ID1 ORDER BY ID2 ASC)
FROM dbo.TableName
)
SELECT ID1, ID2, Name, Phone
FROM CTE WHERE RN = 1