How can i query and return all the rows but with "SUM" added to my query?
Here is my sample query:
select SUM(amount) as total, user_id, username, from table where user_cat = '1';
if I remove SUM
, I get the correct number of rows returned, but when I add SUM
, the row result is decreased.
Any Idea how to do this?
You have noticed it's impossible to make the query in the way you tried as SUM() aggregates the other rows and only one row is displayed. One way to solve this is to separate SUM() in a subquery as described below:
select n.total,
user_id,
username
from table,
(select SUM(amount) as total
from table
where user_cat = '1') n
where user_cat = '1';
I prefer to make this in two separate queries. Now you'll have to deal with the first column and make it invisible. If you use two queries you'll have to deal with the second query. The choice is yours.