在日期分组的多个表中汇总多个列

时间:2010-11-20 19:05:28

标签: sql

我有一个销售和费用表,其行与此类似

SALES

invoiced_on | total | ....
---------------------------
2010-10-01  | 500.00
2010-10-09  | 700.00
...

开支

submitted_on | amount
---------------------
2010-10-01   | 100.00
2010-10-09   | 200.00
...

理想情况下,我会选择三列:

  • sales_total
  • expenses_total

我不熟悉如何在多个聚合列上执行group_by。

2 个答案:

答案 0 :(得分:0)

您可以使用与我发布here

相同的解决方案

诀窍是首先计算不同的总数,然后将它们组合成一个记录。

答案 1 :(得分:0)

应该在MS-SQL中工作,但只是输入并且未经过测试

select DATEPART (WW,x.transDate) as WeekNum,sum(x.SalesAmt) as Sales_total,sum(x.expenseAmt) as expenses_total
from 
(
select invoiced_on as Transdate,amount as SalesAmt,0 as ExpenseAmt 
from Sales
union
select submitted_on as Transdate,0 as SalesAmt,amount as ExpenseAmt 
from expenses
) x
group by DATEPART ( WW , transDate )