求和分析函数或任何其他简单方法

时间:2018-09-07 22:22:07

标签: sql oracle

我在“数据”下方,需要选择所有总和为一列的列

 id size desc1, desc2
 1   13   xxx   yyy
 1   13   xxx   yyy
 1   10   mmm   kkk
 1   10   mmm   kkk

我需要下面的输出

 id  **total_size** desc1 des2
 1    23         xxx   yyy
 1    23         xxx   yyy
 1    23         mmm   kkk
 1    23         mmm   kkk

total_size应该是总和(不同大小)

2 个答案:

答案 0 :(得分:0)

select a.id
    ,a.size
    ,sum(b.size) as 'total_size'
    ,a.desc1
    ,a.desc2
from (
        select *, row_number() over (order by id, size, desc1, desc2) as 'RowNumber'
        from #tmp
      ) a
    left join (
                select *, row_number() over(partition by id, size order by id) as 'dupe'
                from #tmp
               ) b
        on a.id = b.id
        and b.dupe=1
group by a.RowNumber
    ,a.id
    ,a.size
    ,a.desc1
    ,a.desc2

这里不争论,但是您应该真正考虑查看正在使用的数据结构。

  1. 选择数据,添加一列以对行进行编号
  2. 加入数据副本(仅包含不同的记录)
  3. 求和不同记录列表中的size列

答案 1 :(得分:0)

您只需要为SQL中的每一行添加sum(distinct "size") over (partition by id)来计算total_size列:

with tab(id,"size","desc1","desc2") as
(
 select 1 ,13,'xxx','yyy' from dual union all
 select 1 ,13,'xxx','yyy' from dual union all
 select 1 ,10,'mmm','kkk' from dual union all  
 select 1 ,10,'mmm','kkk' from dual
)
select t.id, 
       sum(distinct t."size") over (partition by id) as "total_size",
       t."desc1",t."desc2"
  from tab t;

P.S。 size保留的关键字因此除非被引用,否则不能用作列名。表示为"size"