2

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?

Sachin Verma
  • 789
  • 4
  • 9
  • 15

1 Answers1

7

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)
Abdul Manaf
  • 9,677
  • 16
  • 71
  • 84