我总是蛮力地通过一些丑陋的sql代码来解决与诸如min和max之类的聚合操作相关联的id的问题。我只是想知道是否有正确/干净的方法来解决此问题。假设您具有以下条件:
SELECT 1 AS groupid, 1 AS id, 100 AS val
INTO #a
UNION
SELECT 1, 2, 50
UNION
SELECT 1, 3, 75
UNION
SELECT 2, 2, 120
UNION
SELECT 2, 4, 22
UNION
SELECT 2, 1, 45
注意#1:
id
在groupid
内是唯一注意#2:
对应的第一个IDval
可以具有相同的值,因此在这种情况下,id
列 将是与val
假设我希望结果看起来像这样:
groupid | min_id | min_val | max_id | max_val
1 2 50 1 100
2 3 22 2 120
答案 0 :(得分:3)
您可以使用条件聚合或窗口函数。例如,您可以使用first_value()
:
select distinct group_id,
min(val) over (partition by groupid) as min_val,
first_value(id) over (partition by groupid order by val asc) as min_id,
max(val) over (partition by groupid) as max_val,
first_value(id) over (partition by groupid order by val desc) as max_id
from t;
A,SQL Server不支持将first_value()
作为聚合函数,因此使用了select distinct
快捷方式。
答案 1 :(得分:-1)
使用GROUP BY和类似这样的简单聚合函数
SELECT groupid, MIN(id) AS min_id, MIN(val) as min_val, MAX(id) AS max_id, MAX(val) as max_val
FROM table
GROUP BY groupid