具有最大日期的行的总和

时间:2014-08-29 16:16:22

标签: sql oracle group-by sum

希望你能帮我解决这个问题。我有一张看起来像这样的桌子(对不起,但我的名声不够高,无法张贴图片):

[ACCOUNT] [PROGRAM] [DATE] [AMOUNT]

[500] [P1] [10/10/2014] [4.2]
[500] [P2] [09/08/2010] [5.1]
[501] [P1] [08/02/2010] [2.3]
[501] [P3] [10/11/2014] [9.2]

现在,按帐户分组,我想将金额相加,同时保持程序属于最新日期。我希望在Oracle SQL中实现这一目标:

[ACCOUNT] [PROGRAM] [AMOUNT]

[500] [P1] [9.3] 
[501] [P3] [11.5]
是的,有人可以借给我一只手吗? 非常感谢你!

2 个答案:

答案 0 :(得分:0)

试试这个:

SELECT a.account, b.program, a.amount FROM
(SELECT account, SUM(amount) as amount from table) a INNER JOIN
(SELECT account, program FROM table t 
 WHERE NOT EXISTS (
     SELECT * FROM table 
     WHERE account = t.account and date > t.date)) b 
  ON a.account = b.account

或者这可能也有效:

SELECT t.account, t.program, t.amount 
FROM
(SELECT account, program, SUM(AMOUNT) OVER (PARTITION BY account, program), date  
 FROM table) t 
 WHERE NOT EXISTS 
   (SELECT* from table 
    WHERE account = t.account and date > t.date) b

答案 1 :(得分:0)

这是一个非常常见的问题,没有人有一个很好的答案:" 在符合我的min()/ max()聚合标准的行上显示其他列。&# 34;如果这是一张大表并且性能很重要,那么任何事情都无法触及我概述的方法herehere。尝试:

select account
     , program = substr(val, 9)
     , date = to_date(substr(val, 1, 8))
     , amount
from (  select account
             , amount = sum(amount)
             , val = max(to_char(date, 'YYYYMMDD') + program)  --latest date plus other data you want glued together in a sortable string
        from yourtable 
        group by account) t

如果我的Oracle语法已关闭,我很抱歉 - 我是一个T-SQL人。