SQL选择多个总和?

时间:2009-05-04 20:02:00

标签: sql sql-server tsql

假设我有一张桌子:

SELECT  SUM(quantity) AS items_sold_since_date,
        product_ID
FROM    Sales
WHERE order_date >= '01/01/09'
GROUP BY product_ID

这将返回自特定日期以来销售数量的产品列表。有没有办法不仅选择这个总和,而且还有一个没有where条件的总和?我希望看到每个产品的特定日期以及所有(非日期限制)销售的销售。

5 个答案:

答案 0 :(得分:24)

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

答案 1 :(得分:0)

你可以写

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

答案 2 :(得分:0)

这样的事情?:

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

答案 3 :(得分:0)

如果您希望看到总销售额,那么您将使用sum(sale_amt),并在组中添加sale_amt。我希望它有所帮助。

答案 4 :(得分:0)

您可以使用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;