使用特定ID计算MySQL中的值

时间:2013-12-11 16:34:09

标签: mysql count

好的,这应该很简单:

ID | version | downloads
========================
 1 |   1.0   |     2
 1 |   1.1   |     4
 1 |   1.2   |     7
 1 |   1.3   |     3
 2 |   1.0   |     3
 2 |   2.0   |     3
 2 |   3.0   |    13

无论哪个版本,我都希望获得特定产品(ID)的下载。 这不起作用

SELECT COUNT(*) AS downloads FROM table WHERE ID = 1

应返回2 + 4 + 7 + 3 = 16

4 个答案:

答案 0 :(得分:6)

您的输出表明您要对下载列求和。 所以你必须使用sum aggregate函数..

   SELECT Sum(downloads) AS downloads FROM table WHERE ID = 1

如果您想要每个ID的总和(下载),只需按以下步骤更改查询

 SELECT ID,Sum(downloads) AS downloads FROM table group by ID

如果您需要总记录数,则只使用Count

SELECT Count(*) AS count FROM table WHERE ID = 1

答案 1 :(得分:2)

尝试

SELECT SUM(downloads) AS downloads 
FROM   table 
WHERE  id = 1 

Sum添加了值 您还可以使用group by返回每个id的总和

SELECT SUM(downloads) AS downloads 
FROM   table 
GROUP  BY id 

答案 2 :(得分:2)

SELECT SUM(downloads) FROM table WHERE ID = 1;

答案 3 :(得分:1)

我会去查询一个可以显示所有ID的所有商数据的查询,如果你需要过滤特定的商品数据。

SELECT id,
       SUM(downloads) as TotalDownloads
  FROM table
 GROUP BY id;

如果您需要过滤特定ID,请添加where id = 1

结果如下:

ID | TotalDownloads
========================
 1 | 16
 2 | 19