Oracle:SUM列只有其他列的重复值

时间:2016-06-21 09:01:23

标签: sql database oracle sum

我有如下表:

Name     |Number
------------------
name1    |15 
name1    |7
name2    |10
name3    |9
name4    |11
name4    |4

我想仅返回重复项(名称)的总数(数字),尽管在同一查询中获得(数字)的总计数以获得以下结果:

   Duplicate Count |Total Count
   --------------------------
   37            | 56

4 个答案:

答案 0 :(得分:2)

一种解决方案是使用窗口函数计算每行上每个名称的重复次数,然后对一列中的所有值求和,并仅将记录在另一列上重复的值相加:

with values_cnt as (
select
  count(*) over (partition by name) cnt,
  value
from
  mytable
)
select
  sum(case when cnt>1 then value end),
  sum(value)
from
  values_cnt

答案 1 :(得分:1)

试试这个

WITH tbl
AS (
  SELECT name1
    ,sum(number1) AS sum1
    ,count(*) AS cnt
  FROM tz_Table9
  GROUP BY name1
  )
SELECT (
    SELECT sum(sum1)
    FROM tbl
    WHERE cnt > 1
    ) AS duplicate_count
  ,(
    SELECT sum(sum1)
    FROM tbl
    ) AS total_count
FROM dual

答案 2 :(得分:1)

以这种方式:

with sample_data as (select 'name1' name, 15 num from dual union all
                     select 'name1' name, 7 num from dual union all
                     select 'name2' name, 10 num from dual union all
                     select 'name3' name, 9 num from dual union all
                     select 'name4' name, 11 num from dual union all
                     select 'name4' name, 4 num from dual)
-- End of subquery mimicking a table called "sample_data" with data in it
-- See SQL below:                     
select sum(case when cnt_name > 1 then num end) duplicate_sum,
       sum(num) total_sum
from   (select name,
               num,
               count(*) over (partition by name) cnt_name
        from   sample_data);

DUPLICATE_SUM  TOTAL_SUM
------------- ----------
           37         56

答案 3 :(得分:0)

select (select sum(Number) from Test 
    where Name in (select Name from Test group by Name having count(Name)>1))) as [Duplicate Count], 
(select sum(Number) from Test) as [Total Count]