0

How do you sum the results of a calculated column into one number in SQL?

SELECT
    id, SUM(cost + r_cost) AS Revenue 
FROM
    revenue_table 
WHERE
    signup_date >= '2015-01-01' 
GROUP BY 
    id 
ORDER BY 
    Revenue DESC 
LIMIT 20;

This query displays the revenue to date of the top 20 customers. How can I quickly do a total sum of the Revenue to get the total Revenue of the top 20 guys?

2
  • Two options: you could use Group By id With Rollup, or you could wrap everything in a sub-query and SUM the Revenue column. Commented Mar 2, 2015 at 18:16
  • 1
    Which RDBMS are you using? (that LIMIT looks like MySQL) Commented Mar 2, 2015 at 18:17

1 Answer 1

1

Assuming you're using MySQL:

-- Option 1: Simply put your query in the FROM clause and sum the result
select sum(Revenue)
from (select id, sum(cost + r_cost) as Revenue
      from revenue_table
      where signup_date >= '2015-01-01'
      group by id
      order by Revenue desc
      limit 20) as a

-- Option 2: Use, as suggested by Siyual in his comment, ROLLUP.
--           You'll have to use a subquery too, because 
--           LIMIT is applied after the ROLLUP
select id, sum(a.Revenue) as Revenue
from (select id, sum(cost + r_cost) as Revenue
      from revenue_table
      where signup_date >= '2015-01-01'
      group by id
      order by Revenue desc
      limit 20) as a
GROUP BY id WITH ROLLUP
Sign up to request clarification or add additional context in comments.

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.