2014-06-10 55 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