SQL 对重复的行值求和
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20369868/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sum duplicate row values
提问by SQB
I'm trying to sum the values of rows two of which have duplicate values, the table I have is below:
我正在尝试对其中两行具有重复值的行的值求和,我的表如下:
Table name (Customers)
表名(客户)
value years total
1 30 30
3 10 10
4 15 15
4 25 25
I would ideally like to finally have:
理想情况下,我希望最终拥有:
value years total
1 30 30
3 10 10
4 40 40
I've tried using SELECT DISTINCT
and GROUP BY
to get rid of the duplicate row, also the join in the code below isn't necessary. Regardless both commands come to no avail. Here's my code too:
我已经尝试使用SELECT DISTINCT
并GROUP 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;
But that produces a copy of the first table, any input welcome. Thanks!!!
但这会生成第一个表的副本,欢迎任何输入。谢谢!!!
回答by SQB
SELECT
value,
SUM(years) AS years,
SUM(total) AS total
FROM customers
GROUP BY value;
You want the sum of the years and the sum of the total, per — grouped by— value.
您需要年的总和和总计的总和,按 -按- 值分组。
回答by hegde
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;