简体   繁体   English

在mysql中选择不同的对,并选择第三个值的总和

[英]Select distinct pair in mysql, and the sum of a third value

I'm trying to achieve the following: In a table with three values, for each distinct combination of values in two columns, I wan't to sum the values in the third column. 我正在尝试实现以下目标:在具有三个值的表中,对于两列中值的每种不同组合,我将不对第三列中的值求和。

Eg. 例如。

The following table: 下表:

mysql> select * from test; +------+------+------+ | A | B | num | +------+------+------+ | e | f | 34 | | e | f | 45 | | g | h | 22 | | a | f | 55 | | d | g | 66 | | e | f | 67 | | a | f | 88 | | e | g | 36 | | d | g | 44 | +------+------+------+

I would like: 我想要:

+------+------+ | A | B | +------+------+ | e | f | 146 | g | h | 22 | a | f | 143 | d | g | 110 | e | g | 36 +------+------+

I initially thought this would be a simple combination of DISTINCT and SUM(), but no - can't seem to make any progress. 我最初以为这将是DISTINCT和SUM()的简单组合,但是没有-似乎没有任何进展。 Combining it with a subquery also proved difficult. 将它与子查询相结合也被证明是困难的。 Various similar, but not identical questions have been asked. 已经提出了各种相似但不完全相同的问题。 But not quite the same, and the solutions did not work. 但不是完全一样,解决方案不起作用。

Can anyone help me with this seemingly simple question? 有人可以帮我解决这个看似简单的问题吗?

使用group by

select A,B, sum(num) from test group by A,B;

随身携带:

select sum(num),col1,col2 from table group by col1,col2

Try this query -- 试试这个查询-

SELECT A
    ,B
    ,Sum(Number) AS Total
FROM TableName
GROUP BY A, B
ORDER BY A, B;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM