对重复的行值求和

时间:2013-12-04 07:51:00

标签: sql sum duplicates row distinct

我正在尝试对其中两行具有重复值的行的值求和,我的表格如下:

表名(客户)

value   years   total
1           30    30
3           10    10
4           15    15
4           25    25

我希望最终能够:

value  years   total
1      30      30
3      10      10
4      40      40

我尝试使用SELECT DISTINCTGROUP BY来删除重复的行,也不需要在下面的代码中加入。无论这两个命令都无济于事。这也是我的代码:

SELECT DISTINCT 
  value,
  years,
  SUM(customer.years) AS total 
FROM customer 
INNER JOIN language 
  ON customer.expert=language.l_id 
GROUP BY 
  expert, 
  years;

但是这产生了第一个表的副本,任何输入欢迎。感谢!!!

2 个答案:

答案 0 :(得分:22)

SELECT
   value,
   SUM(years) AS years,
   SUM(total) AS total
FROM customers
GROUP BY value;

您想要年份的总和以及每个 - 值分组的总和的总和。

答案 1 :(得分:1)

SELECT 
  value,
  years,
  SUM(customer.years) AS total FROM (SELECT DISTINCT 
  value,
  years,
  customer.years AS total 
FROM customer 
INNER JOIN language 
  ON customer.expert=language.l_id ) as TABLECUS
GROUP BY 
  expert, 
  years;