2011-12-01 35 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 

希望幫助!