ORACLE SQL - SUM值乘以记录数

时间:2015-11-04 19:58:35

标签: sql oracle sum

我已经通过其他帖子阅读了这个问题,并尝试了他们的解决方案,但没有取得任何进展。如果您能提供任何帮助,我将不胜感激。

我有三个同一个表的实例,从同一个字段中提取不同的OTH_PAY值,具体取决于ERNCD条目。如果单个ERNCD在同一个EFFDT上有多个OTH_PAY条目,则SUM值乘以条目数。

我需要在每个EFFDT上获得每个ERNCD的总和。

SELECT F1.EMPLID, 
SUM(F1.OTH_PAY)"004", 
 SUM(F2.OTH_PAY)"005",
SUM(F3.OTH_PAY)"RAD"
FROM PAY_DATA F1, PAY_DATA F2, PAY_DATA F3
WHERE F1.EMPLID = F2.EMPLID
  AND F1.EMPL_RCD = F2.EMPL_RCD
  AND F1.EMPLID = F3.EMPLID
  AND F1.EMPL_RCD = F3.EMPL_RCD
  AND F1.EFFDT = (SELECT MAX(F1_ED.EFFDT) FROM PAY_DATA F1_ED
                  WHERE F1.EMPLID = F1_ED.EMPLID
                    AND F1.EMPL_RCD = F1_ED.EMPL_RCD)
  AND F2.EFFDT = (SELECT MAX(F2_ED.EFFDT) FROM PAY_DATA F2_ED
                  WHERE F2.EMPLID = F2_ED.EMPLID
                    AND F2.EMPL_RCD = F2_ED.EMPL_RCD)
  AND F3.EFFDT = (SELECT MAX(F3_ED.EFFDT) FROM PAY_DATA F3_ED
                  WHERE F3.EMPLID = F3_ED.EMPLID
                    AND F3.EMPL_RCD = F3_ED.EMPL_RCD)
  AND F1.ERNCD = '004'
  AND F2.ERNCD = '005'
  AND F3.ERNCD = 'RAD'
  AND F1.EMPLID = '12345678'
GROUP BY F1.EMPLID

1 个答案:

答案 0 :(得分:2)

基本思想是使用条件聚合。但是,你在日期也有一个条件,所以这需要一些聪明 - 我的意思是,使用分析函数:

select emplid,
       sum(case when erncd = '004' then oth_pay end) as op_004,
       sum(case when erncd = '005' then oth_pay end) as op_005,
       sum(case when erncd = 'RAD' then oth_pay end) as op_rad
from (select pd.*,
             rank() over (partition by emplid, empl_rcd, erncd order by effdt desc) as seqnum
      from pay_data pd
     ) pd
where seqnum = 1
group by emplid;