将问题与Oracle分组

时间:2012-02-23 18:06:46

标签: sql oracle grouping aggregate-functions aggregation

我有以下数据:

SUM_OF_ALL_PUSHES  |   USER_LOGIN  |   COMPONENT_NAME  | ROW_LST_UPD_TS
-------------------|---------------|-------------------|-------------------------
61                 |   DOMAIN\abc  |   Component A     | 22/02/12 12:58:26.325 PM
14                 |   DOMAIN\xyz  |   Component B     | 22/02/12 05:20:52.565 PM
17                 |   DOMAIN\xyz  |   Component A     | 22/02/12 05:21:58.045 PM
34                 |   DOMAIN\abc  |   Component A     | 22/02/12 05:44:20.274 PM
38                 |   DOMAIN\abc  |   Component A     | 22/02/12 06:28:41.465 PM

我使用以下方法导出数据:

SELECT SUM(Q.SUM_OF_ALL_PUSHES) AS SUM_OF_ALL_PUSHES, Q.USER_LOGIN, Q.COMPONENT_NAME, Q.ROW_LST_UPD_TS FROM( SELECT                
    SUM(REGEXP_SUBSTR(SUBSTR(EVENT_MSG, INSTR(EVENT_MSG, ' ', 1,1), INSTR(EVENT_MSG, ' ', 1,1)) , '[0-9]+')) AS "SUM_OF_ALL_PUSHES", 
    USER_LOGIN,
    COMPONENT_NAME, 
    EVENT_MSG, 
    ROW_LST_UPD_TS
FROM EVENT_MGT.EVENT_LOG
WHERE
ROW_LST_UPD_TS BETWEEN TRUNC(SYSDATE - 1) AND TRUNC(SYSDATE) - 1/86400
AND SUBSTR(EVENT_MSG,1 ,INSTR(EVENT_MSG, 'd', 1,1)) = 'Received'
GROUP BY 
    USER_LOGIN, 
    COMPONENT_NAME, 
    EVENT_MSG, 
    ROW_LST_UPD_TS) Q
GROUP BY COMPONENT_NAME, USER_LOGIN, ROW_LST_UPD_TS 
ORDER BY ROW_LST_UPD_TS ASC

问题是我需要按组件对每个用户的数字求和。因此,在上面的结果集中,我需要聚合第1,4和5列,并将SUM_OF_ALL_PUSHES的值相加,因为每个记录都有用户abc和组件A.

总而言之,我需要删除其他列中的数据重复,并根据用户和组件对第一列中的值求和。所以结果集应如下所示:

SUM_OF_ALL_PUSHES  |   USER_LOGIN  |   COMPONENT_NAME  | ROW_LST_UPD_TS
-------------------|---------------|-------------------|-------------------------
133                |   DOMAIN\abc  |   Component A     | 22/02/12 12:58:26.325 PM
14                 |   DOMAIN\xyz  |   Component B     | 22/02/12 05:20:52.565 PM
17                 |   DOMAIN\xyz  |   Component A     | 22/02/12 05:21:58.045 PM 

请帮忙。

1 个答案:

答案 0 :(得分:1)

听起来你不想按时间戳分组,而是将聚合函数(我猜是MAX)应用于它。

SELECT SUM(Q.SUM_OF_ALL_PUSHES) AS SUM_OF_ALL_PUSHES, Q.USER_LOGIN, Q.COMPONENT_NAME, MAX(Q.ROW_LST_UPD_TS) FROM( SELECT                
    SUM(REGEXP_SUBSTR(SUBSTR(EVENT_MSG, INSTR(EVENT_MSG, ' ', 1,1), INSTR(EVENT_MSG, ' ', 1,1)) , '[0-9]+')) AS "SUM_OF_ALL_PUSHES", 
    USER_LOGIN,
    COMPONENT_NAME, 
    EVENT_MSG, 
    ROW_LST_UPD_TS
FROM EVENT_MGT.EVENT_LOG
WHERE
ROW_LST_UPD_TS BETWEEN TRUNC(SYSDATE - 1) AND TRUNC(SYSDATE) - 1/86400
AND SUBSTR(EVENT_MSG,1 ,INSTR(EVENT_MSG, 'd', 1,1)) = 'Received'
GROUP BY 
    USER_LOGIN, 
    COMPONENT_NAME, 
    EVENT_MSG, 
    ROW_LST_UPD_TS) Q
GROUP BY COMPONENT_NAME, USER_LOGIN 
ORDER BY MAX(Q.ROW_LST_UPD_TS) ASC