user1633525
user1633525

Reputation:

GROUP by and WHERE doesn't work together

Why does this code work:

SELECT year, sum(value)
FROM test
GROUP BY year

And this doesn't?

SELECT year, sum(value)
FROM test
GROUP BY year
WHERE `user` = 1

Upvotes: 1

Views: 1774

Answers (4)

code muncher
code muncher

Reputation: 1682

I'm not expert, but try "HAVING" clause:

SELECT year, sum(value)
FROM test
GROUP BY year
having `user` = 1

Upvotes: 1

Aioros
Aioros

Reputation: 4383

Have you tried

 SELECT year, sum(value) FROM test WHERE user = 1 GROUP BY year

?

Upvotes: 1

xlecoustillier
xlecoustillier

Reputation: 16351

Invert GROUP BY and WHERE clauses :

SELECT year, SUM(value)
  FROM test
 WHERE user = 1
 GROUP BY year

Upvotes: 0

NPE
NPE

Reputation: 500457

GROUP BY needs to come after WHERE:

SELECT year, sum(value) FROM test WHERE user = 1 GROUP BY year 

Upvotes: 7

Related Questions