0

Suppose I have a query select a,b from xyz


The result would be:

a        b
m1     10
m2     20
m3     30

Can I somehow sum all b's something like:

select sum(b) from (select a,b from xyz)

And it will give me result 60. Possible? Stupid question?

5

You need to alias your inner query and use SUM instead of COUNT.

select SUM(b) from (select a,b from xyz) temp_table;

Instead of that you can do like

SELECT SUM(b) FROM xyz;

Example

SELECT userid,score FROM user_score;
+--------+-------+
| userid | score |
+--------+-------+
|      1 |     4 |
|      1 |     5 |
|      1 |     6 |
|      1 |     7 |
|      1 |     8 |
|      1 |     9 |
|      1 |    10 |
|      1 |     2 |
|      1 |     2 |
|      2 |     2 |
|      2 |     3 |
|      2 |     4 |
|      2 |     5 |
|      2 |     6 |
|      2 |     7 |
|      2 |     8 |
+--------+-------+
16 rows in set (0.00 sec)


SELECT SUM(score) FROM (SELECT userid,score FROM user_score ) A;
+------------+
| SUM(score) |
+------------+
|         88 |
+------------+
1 row in set (0.00 sec)

OR

SELECT SUM(score) FROM user_score;
+------------+
| SUM(score) |
+------------+
|         88 |
+------------+
1 row in set (0.00 sec)
  • Does this (select a,b from xyz) temp_table; means (select a,b from xyz) as temp_table? – Sachin Verma Mar 7 '14 at 10:43
  • Gotcha thanks Mr. Abdul Manaf and ypercuber – Sachin Verma Mar 7 '14 at 10:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.