2015-03-02 152 views
0

如何將計算列的結果總和爲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; 

此查詢顯示前20位客戶的收入。我如何快速完成收入的總和來獲得前20名球員的總收入?

+0

兩種選擇:你可以使用'集團通過ID隨着Rollup',或者你可以在一個子查詢包裹的一切,'SUM'收入列。 – Siyual 2015-03-02 18:16:07

+1

您正在使用哪種RDBMS? (即'LIMIT'看起來像MySQL) – Barranka 2015-03-02 18:17:11

回答

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