如何在MS SQL 2008中加入另外五个表

时间:2014-06-10 16:35:52

标签: sql sql-server sql-server-2008

如何加入以下表格以获得结果,如"结果"表:

表:发票

Inv_No  Fk_Rep_ID   Inv_Date    Inv_Amt
3000         202    10/1/2014   35
3001         194    11/1/2014   40

表:返回

Return_ID   FK_Rep_ID   Ret_Date    Ret_Amt
2000             202    15/1/2014   67

表:Credit_ Note

Note_ID FK_Rep_ID   Note_Date   Note_Amnt
1000        NULL    4/2/2014    12

表:Receipt_Items

Fk_Rec_No   FK_Item_No  Item_Type
7788            1000    0
7788            2000    1
7788            3000    2
7788            3001    2

表: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
7788            1000    Credit_ Note    NULL    4/2/2014    12
7788            2000    Return          salman  15/1/2014   67
7788            3000    Invoice         salman  10/1/2014   35
7788            3001    Invoice         Bibin   11/1/2014   40

请查看我的查询:

SELECT tt.*,SR.Rep_Name
FROM
(
    SELECT 
        fk_receipt_no
        ,fk_item_no
        ,CASE Item_type 
            WHEN 0 THEN 'Credit Note'
            WHEN 1 THEN 'Return'
            WHEN 2 THEN 'Invoice'
        END as ITEM_type,
        Case Item_type 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_Note 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
WHERE tt.FK_Receipt_No='7188'

1 个答案:

答案 0 :(得分:2)

SELECT ri.Fk_Rec_No   
      ,ri.FK_Item_No  
      ,A.Item_Type
      ,sr.Rep_Name
      ,A.Inv_Date AS Item_Date
      ,A.Inv_Amt  AS Item_Amt
FROM (
SELECT Inv_No   , 'Invoice' AS Item_Type, Fk_Rep_ID, Inv_Date, Inv_Amt FROM dbo.Invoice
UNION ALL
SELECT Return_ID, 'Return' AS Item_Type, Fk_Rep_ID, Ret_Date, Ret_Amt FROM dbo.[Return]
UNION ALL 
SELECT Note_ID  , 'Credit_ Note' AS Item_Type, Fk_Rep_ID, Note_Date, Note_Amnt FROM dbo.Credit_ Note
 ) A
LEFT JOIN Receipt_Items ri  ON ri.FK_Item_No  = A.Inv_No
LEFT JOIN Sales_Rep sr      ON sr.Rep_ID = A.Fk_Rep_ID

注意

我认为您需要查看您的数据库架构,因为我认为这三个表是不必要的,您应该只有一个表,其中有一个额外的列来标识哪个记录是发票,退货或贷记凭证。您当前的架构违反了数据库规范化的基本规则。