获取 MySQL 查询中每个唯一键的值的总和 [英] Obtaining a sum of values for each unique key in MySQL query

查看:64
本文介绍了获取 MySQL 查询中每个唯一键的值的总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含键列表的表,每个键都与一个数值相关联.我想运行一个 SQL 查询来列出一列中的每个不同的键,以及在另一列中具有该不同键的所有值的总和.这个过程和先选择个体相同

I have a table with a list of keys, each associated with a numeric value. I want to run an SQL query to list each distinct keys in one column and the sum of all values that have that distinct key in another. This process is identical to first selecting individual

  key   |   val
   1    |    4
   2    |    2
   1    |    6
   3    |    7
   2    |   10

会回来:

  key   |   sum
   1    |    10
   2    |    12
   3    |    7

我有:

SELECT DISTINCT key as ukey, SUM(value) as sum from table

但这行不通.有查询吗?

But that doesn't work. Is there a query?

推荐答案

SELECT key, SUM(value) as sum FROM table GROUP BY key

这里是mysql的参考:

Here is reference from mysql:

http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html

这篇关于获取 MySQL 查询中每个唯一键的值的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆