SQL 对 2 个字段进行分组以获得最小值

SQL GROUPING on 2 fields to get the min value

我编写了复杂的查询并获得了如下所示的数据:

+----+---------+-------+------------+
| ID | TYPE_ID | VALUE | SORT_ORDER |
+----+---------+-------+------------+
|  1 |       1 | AAA   |          1 |
|  1 |       1 | BBB   |          2 |
|  2 |       1 | AA1   |          1 |
|  3 |       1 | BB2   |          1 |
|  3 |       1 | AA2   |          2 |
|  3 |       1 | BB3   |          3 |
|  4 |       2 | AAA1  |          1 |
|  4 |       1 | BB4   |          2 |
|  4 |       1 | AA4   |          3 |
|  5 |       2 | BB5   |          1 |
|  5 |       2 | AA5   |          2 |
+----+---------+-------+------------+

但我想获取每个 ID 的最小值 sort_order,并且还考虑 Type_id 1 作为更高优先级。我的分组依据在 table 以上获取 Min(sort_order),因为我在分组依据中包括了每行不同的值。以下是预期结果。

+----+---------+-------+------------+
| ID | TYPE_ID | VALUE | SORT_ORDER |
+----+---------+-------+------------+
|  1 |       1 | AAA   |          1 |
|  2 |       1 | AA1   |          1 |
|  3 |       1 | BB2   |          1 |
|  4 |       1 | BB4   |          2 |
|  5 |       2 | BB5   |          1 |
+----+---------+-------+------------+

请给我你的建议来实现这个目标。

由于您使用的是 SQL Server 2005+,获得结果的最简单方法是使用窗口函数。在这种情况下,您可以使用 row_number() 并按 id 对数据进行分区,但按 type_idsort_order:

对数据进行排序
;with cte as
(
  select id, type_id, value, sort_order,
    rn = row_number() over(partition by id order by type_id, sort_order)
  from yourtable
)
select id, type_id, value, sort_order
from cte
where rn = 1

参见Demo。添加 row_number() 后,您只会 return 行号 = 1 的行。