我有兩個我需要加入的表。我有相同的列兩個SELECT語句除了OrderValue
和SalesTarget
:表A在SQL表中刪除表B中的行JOIN
SELECT
b.TrnYear, b.TrnMonth, b.Branch, b.Salesperson, b.OrderValue
FROM
dbo.vw_jab_Consolidated_Orders as b
INNER JOIN
dbo.vw_jab_SalTargets as a ON a.Sequence2 = b.Salesperson
WHERE
b.TrnYear = '2017'
ORDER BY
a.TrnMonth
SELECT
a.TrnYear, a.TrnMonth, a.Sequence1, a.Sequence2, a.SalesTarget
FROM
dbo.vw_jab_SalTargets as a
WHERE
a.TrnYear = '2017' AND a.SequenceType = 'BR'
GROUP BY
a.TrnYear, a.TrnMonth, a.Sequence1, a.Sequence2, a.SalesTarget
我的問題是,因爲有那裏有沒有OrderValues
個月,該SalesTarget
值被過濾掉了,當我加入這兩個表如下:
SELECT
a.TrnYear, SUM(a.SalesTarget) as SalesTarget, SUM(b.InvoicedSales) AS InvoicedSales
FROM
(SELECT
TrnYear, SUM(SalesTarget) AS SalesTarget
FROM
dbo.vw_jab_SalTargets
WHERE
(SequenceType = 'BR')
GROUP BY
SequenceType, TrnYear) AS A
LEFT JOIN
(SELECT
TrnYear, SUM(ActualSales) AS InvoicedSales
FROM
dbo.vw_jab_Consolidated_Sales
GROUP BY
TrnYear) AS b ON a.TrnYear = b.TrnYear
WHERE
a.TrnYear = '2017'
GROUP BY
a.TrnYear
當你在這裏問一個問題時,不需要SHOUT :-) –
你試過了「左連接」而不是「內連接」嗎? – user2023861
嗨,我試過左連接。 – Jeannette