sql 取聚合函数的值和每个分组的第一个元素

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了sql 取聚合函数的值和每个分组的第一个元素相关的知识,希望对你有一定的参考价值。

-- http://stackoverflow.com/questions/3800551/select-first-row-in-each-group-by-group
--On Oracle 8i+, SQL Server 2005+, PostgreSQL 8.4+, DB2, Firebird 2.1+, Teradata, Sybase, Vertica:

WITH summary AS (
    SELECT p.id, 
           p.customer, 
           p.total, 
           ROW_NUMBER() OVER(PARTITION BY p.customer 
                                 ORDER BY p.total DESC) AS rk
      FROM PURCHASES p)
SELECT s.*
  FROM summary s
 WHERE s.rk = 1
--Supported by any database: But you need to add logic to break ties:

  SELECT MIN(x.id),  -- change to MAX if you want the highest
         x.customer, 
         x.total
    FROM PURCHASES x
    JOIN (SELECT p.customer,
                 MAX(total) AS max_total
            FROM PURCHASES p
        GROUP BY p.customer) y ON y.customer = x.customer
                              AND y.max_total = x.total
GROUP BY x.customer, x.total

--In PostgreSQL this solution is simpler and faster:

SELECT DISTINCT ON (customer)
       id, customer, total
FROM   purchases
ORDER  BY customer, total DESC, id

--Or shorter with positional parameters:

SELECT DISTINCT ON (2)
       id, customer, total
FROM   purchases
ORDER  BY 2, 3 DESC, 1

--当时用法
SELECT x.Id,  -- change to MAX if you want the highest
         x.OccurTime, 
         x.RecvReqSpeed,
		y.最大请求速度
    FROM (select * from gwserverperfdatas where OccurTime <= '2014-04-17 10:28:51' and OccurTime >= '2014-04-17 10:27:51' and InstanceName = 'gwserver:101792:hsdz#b') x
    inner JOIN (SELECT max(p.Id) as rn,
                 max(RecvReqCount) - min(RecvReqCount) as 请求数,
max(RecvReqSpeed) as 最大请求速度,
min(RecvReqSpeed) as 最小请求速度
            FROM (select * from gwserverperfdatas where OccurTime <= '2014-04-17 10:28:51' and OccurTime >= '2014-04-17 10:27:51' and InstanceName = 'gwserver:101792:hsdz#b') p
        ) y ON y.rn = x.Id;

以上是关于sql 取聚合函数的值和每个分组的第一个元素的主要内容,如果未能解决你的问题,请参考以下文章

如何在 Python 中访问聚合函数的值

MySQL窗口函数_聚合函数

MySQL分组、排序

python--pandas分组聚合

R语言如何取分组的第一个值或最后一个值?

sql 分组后求每组中的最大值对应的那条数据