2013-08-22 43 views
-1

不同的表獲取的員工我有兩個表是這樣的:從取決於發票類型

**Invoices:** 
InvoiceId Type Number EmployeeId 
1   A 100 -1 
2   B 200 11 
3   A 300 -1 
4   B 400 13 


**Deliveries:** 
DeliveryId InvoiceId EmployeeId 
1   1   10 
2   2   500 
3   2   501 
4   3   12 
5   4   502 
6   4   503 

發票連接到1個或多個交付。 員工是簽署交貨或發票的人。

在我的數據的邏輯是:如果 只有一個交付加入到發票,我們從交付讀的員工,這是A型。如果有更多的交付,我們從發票閱讀的員工,這是B型

我想獲得:

InvoiceId Number TrueEmployee 
1   100 10 
2   200 11 
3   300 12 
4   400 13 

或最終

InvoiceId Number InvoiceEmployee DeliveryEmployee 
1   100 whatever  10 
2   200 11    whatever 
3   300 whatever  12 
4   400 13    whatever 

我試過

Select InvoiceId,Number,Invoices.EmployeeId,Deliveries.EmployeeId 
from Invoices inner join Deliveries 
on Invoices.InvoiceId=Deliveries.InvoiceId 

但它會返回多行每張發票,如果有超過1個送連接到它

任何想法? 如果有問題,我正在使用Ms SQL Server。

回答

2

這裏是沒有分組的一個版本,但有更多的選擇性LEFT JOIN

SELECT i.InvoiceId, 
     i.Number, 
     CASE i.Type WHEN 'A' THEN 999 ELSE i.EmployeeId END iEmployeeId, 
     COALESCE(d.EmployeeId,999) dEmployeeId 
FROM invoices i 
LEFT JOIN deliveries d ON i.Type='A' 
         AND d.InvoiceId = i.InvoiceId 

http://sqlfiddle.com/#!3/0b8738/4

隨便挑,隨便你最適合。 (在我的示例中,我使用999作爲'whatever'的值。)

+0

Thanks!這真的適用於我 - 只有在發票類型適當的情況下才加入交付。沒有更多的雙排。 – RRM