2014-09-01 43 views
-1

我有2個表,我想從單個查詢中獲取數據集以在圖表中顯示它。 但我正在執行錯誤。只有年和expyear和月和exp月是列可能有共同的數據。每一行都有其年份和月份字段。單選查詢中兩個不同表上的求和函數

這裏是我試圖查詢:

select 
    t.transExpense 
    g.grocExpense 
from 
    (Select sum(traexpense) as transExpense from 
       transportExpense where Year="2014") t, 
    (Select sum(groexpense) as grocExpense from 
       groceryExpense where expYear="2014") g 

請幫助。

+1

你得到了什麼錯誤信息? – Thilo 2014-09-01 04:38:45

回答

2

t.transExpense後面缺少逗號。

但是,要返回單個值,則不需要將子查詢放入FROM子句中;你可以直接在SELECT中使用它們作爲標量子查詢:

SELECT (SELECT SUM(traexpense) 
     FROM transportExpense 
     WHERE Year = '2014' 
     ) AS transExpense, 
     (SELECT SUM(groexpense) 
     FROM grocExpense 
     WHERE expYear = '2014' 
     ) AS grocExpense; 
+0

感謝您糾正我。獲得某些優化是有意義的。有時候我們會忘記像逗號這樣的小事來破壞我們的一天。 – SOAMad 2014-09-01 10:01:21

2

添加逗號所選字段之間:

select 
t.transExpense, -- << right there 
g.grocExpense 
from 
(Select sum(traexpense) as transExpense from transportExpense where Year="2014") t, 
(Select sum(groexpense) as grocExpense from groceryExpense where expYear="2014") g 
0

它可以通過連接查詢來解決。例如:

SELECT sum(t.traexpense) as t.transExpense, sum(g.groexpense) as g.grocExpense 
from transportExpense t LEFT JOIN groceryExpense g ON t.fieldname=g.fieldname 
where g.expYear=2014 and t. Year=2014 

如果您的表沒有任何公用字段進行連接,則可以使用t.Year和g.expYear進行連接。

相關問題