如何将计算列的结果总结为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;
此查询显示前20位客户的收入。如何快速完成收入总额以获得前20名员工的总收入?
答案 0 :(得分:1)
假设你正在使用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