2017-04-10 77 views
0

我這裏有單獨的查詢如下:加入SQL查詢不會放棄希望的結果

SELECT c.id 
FROM claim c, 
     company co, 
     customer cu 
WHERE c.company_id = co.id 
     AND c.customer_id = cu.id 
     AND co.company_code = 'LTO' 
     AND cu.customer_no = '021540' 
     AND c.invoice_number IS NOT NULL 
     AND c.invoice_date IS NULL 
     AND c.invoice_number = '20170331' 

SELECT Sum(price) 
FROM replaced_part 
WHERE claim_id IN (628099, 674047, 1182523, 1282549, 
        1479834, 1480585, 1487452, 1515238); 

SELECT Sum(price) 
FROM allowance 
WHERE claim_id IN (628099, 674047, 1182523, 1282549, 
        1479834, 1480585, 1487452, 1515238); 

我是想組一起放入上述所有查詢一個使用SQL相等加入如下:

select co.company_Code, 
     cu.customer_No, 
     c.invoice_Number, 
     sum(r.price), 
     sum(a.price) 
FROM claim c INNER JOIN company co ON c.COMPANY_ID=co.ID 
       INNER JOIN customer cu ON c.CUSTOMER_ID=cu.ID 
       INNER JOIN replaced_part r ON r.claim_id=c.id 
       INNER JOIN allowance a ON a.claim_id = c.id 
WHERE co.company_code = 'LTO' and cu.customer_no='021540' and 
     c.INVOICE_NUMBER is not null and c.INVOICE_DATE is null and 
     c.INVOICE_NUMBER='20170331' 
GROUP BY co.company_Code, cu.customer_No, c.invoice_Number 

但我沒有得到所需的結果(查詢執行成功,但總和是不正確的),因爲我正在運行上面定義的3個單獨的查詢後...在我的查詢使用equi連接創建的這裏有什麼問題?

表之間的關係是索賠 - >(一對一) - >公司 - >(一對一) - >客戶 - >(一對多) - >替換部分 - >(一對多) - >津貼

+0

使用適當的ANSI連接(INNER JOIN與ON子句)重寫,而不是隻列出表的古老的非標準語法,然後使用WHERE子句過濾初學者。 – pmbAustin

+0

爲每個查詢使用一個'CTE',然後加入結果 –

+0

使用INNER JOIN重寫的查詢 –

回答

0

請儘量使用左側加入了Replaced_Part和津貼

select co.company_Code 
    , cu.customer_No 
    , c.invoice_Number 
    , (SELECT sum(r.price) FROM replaced_part r WHERE r.claim_id = c.id) 
    , (SELECT sum(a.price) FROM allowance a WHERE a.claim_id = c.id) 
FROM claim c 
INNER JOIN company co 
    ON c.COMPANY_ID=co.ID 
INNER JOIN customer cu 
    ON c.CUSTOMER_ID=cu.ID  
WHERE co.company_code = 'LTO' 
AND cu.customer_no='021540' 
AND c.INVOICE_DATE is null 
AND c.INVOICE_NUMBER='20170331' 
GROUP BY co.company_Code 
, cu.customer_No 
, c.invoice_Number 
+0

結果wendy中沒有變化,因爲使用左連接進行賦值並且替換部分在輸出中沒有任何影響 –

0

嘗試使用臨時表,將所有的表,使一個臨時表,再火上表的條件。

例子:

select co.company_Code, 
     cu.customer_No, 
     c.invoice_Number, 
     sum(r.price), 
     sum(a.price) 
into #temp from (claim c 
       INNER JOIN company co ON c.COMPANY_ID=co.ID 
       INNER JOIN customer cu ON c.CUSTOMER_ID=cu.ID 
       INNER JOIN replaced_part r ON r.claim_id=c.id 
       INNER JOIN allowance a ON a.claim_id = c.id 

,然後用你的條件對#TEMP。像

select * from #temp 
WHERE company_code = 'LTO' and customer_no='021540' and 
     INVOICE_NUMBER is not null and INVOICE_DATE is null and 
     INVOICE_NUMBER='20170331' 
GROUP BY company_Code, customer_No, invoice_Number 

希望這會對你有用。