SQL group by:选择另一列具有最小/最大值的值

时间:2017-09-05 07:37:13

标签: sql sql-server

我希望按一列分组,获取第二列的最小值和最大值,并且(这是棘手的部分!)从第三列获取值,其中第二列在组中具有其最小值。 / p>

示例:

MyTable的:

ID     TS     GRP
==================
 1     20      A
 2     20      B
 3     10      A
 4     30      A
 5     10      B
 6     40      A

期望的结果(ID应该是TS最小的记录中的值):

ID    MIN_TS   MAX_TS   GRP
============================
 3      10       40      A
 5      10       20      B

通常,分组查询非常简单:

SELECT <???> AS ID, MIN(TS) AS MIN_TS, MAX(TS) AS MAX_TS, GRP
FROM MyTable
GROUP BY GRP

但ID部分怎么样?它不会以这种方式进行分组,对吧?但为什么?什么是最好的解决方法?

1 个答案:

答案 0 :(得分:2)

在子查询中进行聚合,然后在另一个子查询中查找每个组的ID:

SELECT
  (SELECT TOP(1) id FROM MyTable WHERE grp = agg.grp ORDER BY ts DESC) AS id,
  min_ts, max_ts, grp
FROM (SELECT min(ts) AS min_ts, max(ts) AS max_ts, grp
      FROM MyTable
      GROUP BY grp) agg

或使用窗口功能:

SELECT id, min_ts, max_ts, grp
FROM (SELECT 
        id,
        min(ts) OVER (PARTITION BY grp) min_ts,
        max(ts) OVER (PARTITION BY grp) max_ts,
        grp,
        row_number OVER (PARTITION BY grp ORDER BY ts) rn
      FROM MyTable)
WHERE rn = 1;

此查询使用窗口函数计算每个组的min_tsmax_ts,然后过滤为仅包含每个组的第一行(按ts排序)。