如何按日期对2个表中的列进行求和

时间:2011-12-01 19:06:50

标签: sql sql-server

我有两张桌子:

table1 contains (amount, date)
table2 contains (amount, revenue, date)

我需要:

sum table1.amount + table2.amount, sum table2.revenue
according to table1.date and table2.date

像:

select sum(table1.amount + table2.amount), sum(table2.revenue)
from table1,table2
where table1.date and table2.date = '2008-02%'

2 个答案:

答案 0 :(得分:1)

这将显示所有年度的结果:

with table3 (amount, revenue, date) as
(
    select amount, 0, date from table1
    union all
    select cost, revenue, date from table2
)
select year(date), month(date), sum(amount), sum(revenue)
from table3
group by year(date), month(date)
order by year(date), month(date);

答案 1 :(得分:0)

SELECT SUM(amount), SUM(revenue)
FROM (
        SELECT amount, 0 as revenue, theDate 
        FROM table1
        UNION ALL 
        SELECT amount, revenue, theDate 
        FROM table2 ) AS DERIVED
WHERE   (MONTH(DERIVED.theDate) = 2 
AND YEAR(DERIVED.theDate) = 2008)   

您可以将where子句放在UNION语句中,我可能会这样做,但这样可以简化示例。如果你在等式中有键,我会用完全外连接或类似的东西做不同的但是对你的例子来说这是有效的。

如果您希望显示日期并查看所有日期的总和,则以下内容将起作用:

SELECT SUM(amount), SUM(revenue), theDate 
FROM (
        SELECT amount, 0 as revenue, theDate 
        FROM table1
        UNION ALL 
        SELECT amount, revenue, theDate 
        FROM table2 ) AS DERIVED
GROUP BY theDate

希望有所帮助!