如何在Oracle中进行计数后选择最大值?

时间:2018-08-23 14:25:51

标签: sql oracle oracle11g

我有一个查询:

SELECT
  CST_CON_ID as ID_USER,
  X_TYPE_FOURTH_LVL as ELEMENT_TYPE,
  COUNT(X_TYPE_FOURTH_LVL) as T_REPEAT
FROM
  SIEBEL.S_SRV_REQ
GROUP BY
   CST_CON_ID,
   X_TYPE_FOURTH_LVL
ORDER BY
   CST_CON_ID;

运行时会返回以下信息:

ID_USER      ELEMENT_TYPE    T_REPEAT
1-1HQR-1380   REPOSITION      3
1-1HQR-1380   CANCELED        4
1-1HQR-1380   INFORMATION     1
1-1HQR-1380   SELLS           90
1-1HQR-1380   PROMOTIONS      3
1-1HQR-1380   ACCOUNTS        5
1-1HQR-1250   ACTIONS         34
1-1HQR-1250   PROG            60
1-1HQR-1250   INFORMATION     3
1-1HQR-1560   SELLS           40
1-1HQR-1560   BUYS            2
1-1HQR-1560   REPOSITION      1
1-1HQR-1560   PROMOTIONS      70

但是现在我只想为每个ID_USER提取T_REPEAT的最大值。 我想要的预期输出将如下所示:

ID_USER      ELEMENT_TYPE    T_REPEAT
1-1HQR-1380   SELLS           90
1-1HQR-1250   PROG            60
1-1HQR-1560   PROMOTIONS      70

是否可以仅使用单个查询获得此输出?

2 个答案:

答案 0 :(得分:1)

一种选择是使用row_number()

SELECT ID_USER, ELEMENT_TYPE, T_REPEAT
FROM (SELECT CST_CON_ID as ID_USER, X_TYPE_FOURTH_LVL as ELEMENT_TYPE,
             COUNT(X_TYPE_FOURTH_LVL) as T_REPEAT,
             ROW_NUMBER() OVER (PARTITION BY CST_CON_ID ORDER BY COUNT(X_TYPE_FOURTH_LVL) DESC) AS Seq
      FROM SIEBEL.S_SRV_REQ
      GROUP BY CST_CON_ID, X_TYPE_FOURTH_LVL
     ) t
WHERE Seq = 1;

编辑:如果您与count有联系,则使用dense_rank()函数:

答案 1 :(得分:-1)

将当前语句包装在子查询中。

SELECT ID_USER, ELEMENT_TYPE, MAX(T_REPEAT) 
FROM (
   SELECT
     CST_CON_ID as ID_USER,
     X_TYPE_FOURTH_LVL as ELEMENT_TYPE,
     COUNT(X_TYPE_FOURTH_LVL) as T_REPEAT
   FROM
     SIEBEL.S_SRV_REQ
   GROUP BY
      CST_CON_ID,
      X_TYPE_FOURTH_LVL
   ORDER BY
      T_REPEAT
   )
GROUP BY ID_USER