2014-06-10 56 views
-1

如何加入下表,獲取引起像 「結果」 表:聯接和SQL Server循環2008

表:發票

Inv_No Fk_Rep_ID  Inv_Date  Inv_Amt 
3000    202  10/1/2014  35 
3001    194  11/1/2014  40 
3002    180  15/1/2014  55 

表:返回

Return_ID FK_Rep_ID  Ret_Date Ret_Amt 
2000    202  17/1/2014 67 
2001  194 15/1/2015 43 

表:信用

Credit_ID FK_Rep_ID credit_Date credit_Amnt 
1000   NULL  4/2/2014 60 
1001   202  5/2/2014 12 

表:Deb它

Debit_ID FK_Rep_ID   Debit_Date Debit_Amnt 
400   NULL   4/5/2014 600 
4001    194   5/5/2014 110 

表:Receipt_Items

Fk_Rec_No FK_Item_No  Item_Type Rec_Item_ID 
7787    1000    2 1 
7788    2000    1 1 
7788    3000    0 2 
7788    3001    0 3 
7788    3002    0 4 
7788    4000    3 5 
7788    4001    3 6 
7789    1001    2 1 

表:SALES_REP

Rep_ID  Rep_Name 
180   Vinu 
194   Bibin 
202   Salman 

結果

Fk_Rec_No Fk_Item_No Item_Type Rep_Name Item_Date Item_Amt 
7787 1000 Credit NULL 4/2/2014 -60 
7788 2000 Return salman 15/1/2014 -67 
7788 3000 Invoice salman 10/1/2014 35 
7788 3001 Invoice Bibin 11/1/2014 40 
7788 3002 Invoice Vinu 12/1/2014 55 
7788 4000 Debit NULL 4/5/2014 600 
7788 4001 Debit Bibin 5/5/2014 110 
7789 1001 Credit Salman 5/2/2014 -12 

查詢:

SELECT tt.*,SR.Rep_Name 
    FROM(SELECT 
    fk_receipt_no 
    ,fk_item_no 
    ,CASE Item_type 
    WHEN 0 THEN 'INVOICE' 
    WHEN 1 THEN 'Return' 
    WHEN 2 THEN 'Credit' 
    WHEN 3 THEN 'Debit' 
    END as ITEM_type, 
    Case Item_type when 1 then '-'+Cast(Item_Amnt as varchar(50)) 
    when 2 then '-'+Cast(Item_Amnt as varchar(50)) 
    else Cast(Item_Amnt as varchar(50)) End Item_Amnt 
    ,COALESCE(R.FK_Rep_ID,C.FK_Rep_ID,I.FK_Rep_ID) as FK_Rep_ID 
    ,COALESCE(R.Ret_Date,C.Note_Date,I.Inv_Date) as Item_Date 
    FROM Recp_Item RI LEFT JOIN [Return] R ON RI.FK_Item_no=R.Return_ID 
    LEFT JOIN Credit C ON RI.FK_Item_No=C.Note_ID 
    LEFT JOIN Invoice I ON RI.FK_Item_No=I.Inv_No 
    ) tt LEFT JOIN [Sales Rep] SR ON SR.Rep_ID=tt.FK_Rep_ID 
+1

'得到像「結果」表中的結果:'它在哪裏? – Rahul

+0

什麼結果表? ^^ – gustavodidomenico

+0

我不能在這裏發表我的查詢,它有一些格式化錯誤 – sallu

回答

2

您可能應該提及FK_Item_No有時指不同的事物,如Credit_ID。 這種多用途FK 幾乎總是會導致它可以表示的每種類型的項目的聯合。

這是僞代碼,我希望你提供所有繁瑣的加入標準,因爲你應該可以這樣做。

通知左聯接用於將代表表,因爲你有一些空FK的

在每一個選擇別名用於標準化的列名,如credit_amnt =>Item_Amt。從技術上講,只有在連接中的第一次選擇時才需要,只要其他人的順序相同,但我通常會爲了可讀性而爲所有工會進行選擇。

Select * From 
(
    Select ri.Fk_Rec_No, Credit_ID as Fk_Item_No, it.Name as Item_Type, 
    r.Rep_Name, c.credit_Date as Item_Date, c.credit_Amnt as Item_Amt 
    From Credit c inner join Receipt_Items ri left join Rep r 
    --join with your item type table you don't show 

    Union 

    Select ri.Fk_Rec_No, Debit_ID as Fk_Item_No, it.Name as Item_Type, 
    r.Rep_Name, c.Debit_Date as Item_Date, d.Debit_Amnt as Item_Amt 
    From Debit d inner join Receipt_Items ri left join Rep r 
    --join with your item type table you don't show 

    Union 
    ... 

) as typesUnion 
Order By Fk_Rec_No, Fk_Item_No