Oracle SQL获取一组分组结果中每个组的MAX值行

时间:2019-03-08 14:39:03

标签: sql oracle greatest-n-per-group

通过运行我得到了以下结果

SELECT 
       REV_USAGE_DATA.DDATE, 
       REV_USAGE_DATA.SEGMENT, 
       COUNT(*) AS Freq
FROM CADA_PERMSISDN_DASH REV_USAGE_DATA
GROUP BY 
       REV_USAGE_DATA.DDATE,
       REV_USAGE_DATA.SEGMENT
ORDER BY 
REV_USAGE_DATA.DDATE

result set

对于每个日期,我想获取FREQ列中具有最高值的整行。我该如何实现?

3 个答案:

答案 0 :(得分:1)

您可以使用CTE

WITH CTE0 AS 
(
  SELECT 
       REV_USAGE_DATA.DDATE, 
       REV_USAGE_DATA.SEGMENT, 
       COUNT(*) AS Freq
  FROM CADA_PERMSISDN_DASH REV_USAGE_DATA
  GROUP BY 
       REV_USAGE_DATA.DDATE,
       REV_USAGE_DATA.SEGMENT
)
SELECT 
  DDATE,
  SEGMENT, 
  FREQ
FROM CTE0 
WHERE (DDATE, SEGMENT, FREQ) IN (
  SELECT DDATE, MAX(SEGMENT), MAX(FREQ)
  FROM CTE0 
  GROUP BY DDATE
)

答案 1 :(得分:1)

使用ROW_NUMBER()

SELECT DDATE, SEGMENT, Freq
FROM (SELECT REV_USAGE_DATA.DDATE, REV_USAGE_DATA.SEGMENT, 
             COUNT(*) AS Freq,
             ROW_NUMBER() OVER (PARTITION BY REV_USAGE_DATA.DDATE ORDER BY COUNT(*) DESC) as seqnum
      FROM CADA_PERMSISDN_DASH REV_USAGE_DATA
      GROUP BY REV_USAGE_DATA.DDATE,REV_USAGE_DATA.SEGMENT
     ) rud
WHERE seqnum = 1
ORDER BY REV_USAGE_DATA.DDATE;

如果您在日期上有联系并且想要所有最大值,请改用RANK()

答案 2 :(得分:0)

大量类似的解决方案!这是我的。 使用CTE计算哪个记录的频率最高(类似于行号),然后选择它们

WITH data AS
(
  SELECT 
       REV_USAGE_DATA.DDATE, 
       REV_USAGE_DATA.SEGMENT, 
       COUNT(*) AS Freq
  FROM CADA_PERMSISDN_DASH REV_USAGE_DATA
  GROUP BY 
         REV_USAGE_DATA.DDATE,
         REV_USAGE_DATA.SEGMENT
),
maxRecords AS
(
  SELECT DDATE, SEGMENT, FREQ, 
         CASE WHEN FREQ = MAX(FREQ) OVER(PARTITION BY DDATE) THEN 1 ELSE 0 END HighestFreq
  FROM data
)

SELECT DDATE, SEGMENT, FREQ
FROM maxRecords
WHERE HighestFreq = 1
ORDER BY DDATE;