幫助

2010-01-20 164 views
0

我有一個問題,有三個表幫助

Table A 

ID  Employee  
1   1  
2   2 
3   3 


Table B 
Id  EMployee  HoursWorked   HoursCode 
1   1     10    Basic Hours 
2   1     20    Holiday Pay 
3   2     10    Basic hours 
4   2     15    OverTime 

Table C 
ID  Employee   Payments   PayCode 
1   1     100    Bonus 
2   2     150    Bonus 
3   2     250    Student Loan 

我想記錄了在最短的線路,這些表的,所以我可以有一個線,說

id  Employee   Hour    HoursCode  Payments  PayCode 
1   1     10    Basic Hours  100   Bonus  
2   1     20    Holiday Pay  null   null 
3   2     10    basic hours  150   Bonus 
4   2     15     OverTime  250   Student loan 

我已經花了年齡試圖讓它...但不要讓空在它與100名獎金出來,在第二行員工1

2號線是有辦法可以做到這一點請幫助

+1

問題是表B和表C之間沒有鏈接......例如,在結果中顯示員工1的100美元是爲他的「基本工時」工作支付的......但我們如何知道......在您的數據中,我們知道100美元的「付款」不是他的「假期付款」? – 2010-01-20 10:32:25

+1

表B和C如何關聯? – Paddy 2010-01-20 10:32:34

+0

B和C僅通過員工編號關聯。 – Bikram 2010-01-20 11:05:59

回答

3
WITH bn AS 
     (
     SELECT *, ROW_NUMBER() OVER (PARTITION BY employee ORDER BY id) AS rn 
     FROM b 
     ), 
     cn AS 
     (
     SELECT *, ROW_NUMBER() OVER (PARTITION BY employee ORDER BY id) AS rn 
     FROM c 
     ) 
SELECT * 
FROM bn 
FULL JOIN 
     cn 
ON  bn.employee = cn.employee 
     AND bn.rn = cn.rn 
ORDER BY 
     COALESCE(bn.employee, cn.employee), COALESCE(bn.rn, cn.rn) 
+0

非常感謝你,它的工作原理。非常感激.. – Bikram 2010-01-20 15:07:01