简体   繁体   English

SQL中的列总和

[英]Sum Column Results in SQL

How do you sum the results of a calculated column into one number in SQL? 在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. 此查询显示迄今为止排名前20位的客户的收入。 How can I quickly do a total sum of the Revenue to get the total Revenue of the top 20 guys? 我如何快速计算收入的总和以获得前20名球员的总收入?

Assuming you're using MySQL: 假设您正在使用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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM