SQL 选择多个总和?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/821751/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
SQL Selecting multiple sums?
提问by Joel Coehoorn
Let's say I have a table:
假设我有一张桌子:
SELECT SUM(quantity) AS items_sold_since_date,
product_ID
FROM Sales
WHERE order_date >= '01/01/09'
GROUP BY product_ID
This returns a list of products with the quantity sold since a particular date. Is there a way to select not only this sum, but ALSO the sum WITHOUT the where condition? I'd like to see sales since a particular date for each product alongside all (not date limited) sales.
这将返回具有自特定日期以来销售数量的产品列表。有没有办法不仅选择这个总和,而且还选择没有 where 条件的总和?我希望看到自特定日期以来每种产品的销售额以及所有(不受日期限制)的销售额。
回答by Joel Coehoorn
SELECT SUM(CASE WHEN order_date >= '01/01/09' THEN quantity ELSE 0 END) AS items_sold_since_date,
SUM(quantity) AS items_sold_total,
product_ID
FROM Sales
GROUP BY product_ID
回答by Sadegh
you can write
你可以写
SELECT SUM(quantity) AS items_sold_since_date,(SELECT SUM(quantity) AS items_sold_since_date FROM Sales
GROUP BY product_ID) as items_sold,
product_ID
FROM Sales
WHERE order_date >= '01/01/09'
GROUP BY product_ID
回答by rein
something like this?:
像这样的东西?:
SELECT SUM(quantity) AS items_sold_since_date,
total_items_sold = (SELECT SUM(quantity) from Sales GROUP BY product_ID),
product_ID
FROM Sales
WHERE order_date >= '01/01/09'
GROUP BY product_ID
回答by rein
If you like to see total sales alongside, then you would use sum(sale_amt), and in the group by add the sale_amt. I hope it helps.
如果您想在旁边查看总销售额,则可以使用 sum(sale_amt),并在组中添加 sale_amt。我希望它有帮助。
回答by gabor
You could use GROUP BY to split up the Sales based on date. In Oracle you could say:
您可以使用 GROUP BY 根据日期拆分销售额。在 Oracle 中,您可以说:
select count(*)
,case when order_date >= '01/01/09' then 'after' else 'before' end
from log
group by case when order_date >= '01/01/09' then 'after' else 'before' end;