且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在SQL Server中按多列分组

更新时间:2022-11-27 15:07:37

这里是一个使用子查询从Person表中识别第一个匹配项"的解决方案,我将其解释为是指具有最低要求的人每个城市组的ID值.

Here is a solution which uses a subquery to identify the "first match" from the Person table, which I have interpreted to mean the person with the lowest id value in each city group.

SELECT t1.Id,
       t1.Name AS PersonName,
       t2.Name AS CityName
FROM Person t1
INNER JOIN City t2
    ON t1.CityId = t2.Id
INNER JOIN
(
    SELECT CityId, MIN(Id) AS minId
    FROM Person
    GROUP BY CityId
) t3
    ON t1.CityId = t3.CityId AND t1.Id = t3.minID

可能还有一种使用窗口函数执行此操作的方法.

There is probably also a way to do this with window functions.