0

Is it possible to get the sum of a column and all the column itself using one query? I mean, I need SUM(Result.num) and the individual Result.num as well, but I dont want to use two separate queries for the purpose? the idea result might be the SUM as another column in the result. Result might look like: col1 Result.num1, SUM Result.num2, SUM Result.num3, SUM ....

 SELECT SUM(Result.num) 
   FROM (SELECT COUNT(colA) AS num 
           FROM Table1 
       GROUP BY colB) AS Result;

 SELECT Result.num 
   FROM (SELECT COUNT(colA) AS num 
           FROM Table1 
       GROUP BY colB) AS Result;
1
  • Why not use two queries? how would you like your result to be represented? Commented Jun 17, 2011 at 2:38

3 Answers 3

4

The answer is that you will do two statements but you can return the results in one result set. You can do that with a UNION ALL statement. Just take your two queries and put a UNION ALL statement between them. It will look like this:

 SELECT Result.num 
   FROM (SELECT COUNT(colA) AS num 
           FROM Table1 
       GROUP BY colB) AS Result;
 UNION ALL
 SELECT SUM(Result.num) 
   FROM (SELECT COUNT(colA) AS num 
           FROM Table1 
       GROUP BY colB) AS Result;

I switched the order around so that your SUM value would be at the end but you could put it at the beginning if you would like.

Sign up to request clarification or add additional context in comments.

2 Comments

will mysql execute the subquery twice to get the result set?
The sub will be executed once for each side of the union so...yes
1

Pretty sure you just need to union your queries

 SELECT SUM(Result.num) FROM (SELECT COUNT(colA) AS num FROM Table1 group by colB) AS Result
union all
 SELECT Result.num FROM (SELECT COUNT(colA) AS num FROM Table1 group by colB) AS Result;

Comments

0

The WITH ROLLUP clause might be useful to you here.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.