Xaver
Xaver

Reputation: 11662

Count values in MySQL with specific ID

Ok, this should be simple:

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

I like to get the downloads of a specific product (ID) no matter which version. This doesn't work

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

should return 2 + 4 + 7 + 3 = 16

Upvotes: 1

Views: 9129

Answers (4)

Sam
Sam

Reputation: 2761

Try

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

Sum adds the values You can also use group by to return the sum for each id

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

Upvotes: 2

Haji
Haji

Reputation: 2077

Your output says that you want to sum the downloads column. so you have to use sum aggregate function..

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

If you want sum(downloads) for each ID,Just change the query as follow

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

If you need total record counts then only use Count

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

Upvotes: 8

Jorge Campos
Jorge Campos

Reputation: 23361

I would go for a query that could show you all SUMs from all IDs then if you need you filter one in specific.

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

If you need to filter a specific id just add where id = 1

The result for this would be:

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

Upvotes: 1

abasterfield
abasterfield

Reputation: 2292

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

Upvotes: 2

Related Questions