2011-12-01 56 views
1

总结列我有2个表:如何从2个表按日期

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%' 
+0

如果在表1日期“2008-02-01”的行,但在表2中没有对应的行应该发生什么,或反之亦然? –

+0

你想在2008年2月的所有记录中找到这个吗? –

+0

是的,我想feb 2008年的记录,如果为空,那么数据应该显示为空 –

回答

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); 
+0

好吧,我忘了告诉表2列名称“金额”实际上命名为“成本”。我运行它不显示数量正确的数据。但收入正确 –

+0

更正了列名 – Raihan

+0

谢谢。它的工作原理 –

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) 

你可以把UNION语句中的where子句,我可能会这样简化前者的操作充足。如果你在方程中有键,我会用完全的外部连接或类似的方法来做这个,但对你的例子来说这是有效的。

如果你想要的日期显示和查看所有日期的款项,则以下将工作:

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 

希望帮助!