2016-09-16 72 views
0

IM面臨SQL有點問題加入SQL鮮明加入

我有2個表

*1st table*     *2nd table* 
Reference Name    Reference Amount 
123   Test1   123   52 
145   Test2   232   22 
123   Test3   123   33 
555   Test4   145   44 
123   Test5   656   55 

我需要這樣的東西

select distinct(a.reference), sum(b.amount) from 1st a left join 2nd b ON a.Reference = b.Reference group by a.reference 

這看起來很簡單,對我來說它做什麼 - 它給我多次SUM參考是123,所以它會給我(52 + 33)* 3

我應該使用什麼來獲得每個引用的唯一SUM?

Thx!

編輯:

最終的結果應該看起來像

123 85 
145 44 
+0

請編輯您的問題,並提供您正在尋找的結果。你不會在任何地方解釋你想要什麼。 –

回答

1

執行distinctjoin

select a.reference, sum(b.amount) 
from (select distinct reference from a) a left join 
    b 
    a.Reference = b.Reference 
group by a.reference; 

你幾乎永遠不會需要使用select distinctgroup by

+0

現在工作!謝謝 – DaytonaGuy

0

您的查詢是不正確,

,因爲我們通過有一羣你不應該使用不同的..

所以,你應該是有可能的,

select a.reference, sum(b.amount) from 1st a 
left join 2nd b ON a.Reference = b.Reference group by a.reference 
0

你也可以使用一個CTE來解決您的問題:

WITH cte 
AS 
(

SELECT DISTINCT reference FROM 1st 

) 

SELECT a.reference, SUM(b.amount) 
FROM cte a 
LEFT JOIN 2nd b ON a.Reference = b.Reference 
GROUP BY a.reference