在sql中连接两个或多个表

时间:2014-01-15 13:39:14

标签: sql sql-server

我有三张表,如下所述:

TransactionHeader

ID    |   ProcessID   |   BillingHeaderID
1             1                  1
2             2                  2

TransactionDetail

ID    |   ProcessID   |   BillingDetailID
1             1                  1
2             1                  2

BillingDetail

BillingDetailID |   BillingHeaderID  |   Amount
3                      2                  10000
4                      2                  20000
5                      2                  10000
6                      1                  10000 
7                      1                  10000

到目前为止,我正在这样做

select
    b.ID as ID_TransacHeader,
    a.ID as ID_TransacDetail,
    b.ProcessID
    ,a.BillingDetailID as Before
    ,c.BillingDetailID as After
from TransactionDetail a
inner join TransactionHeader b on a.ProcessID = b.ProcessID
inner join billingdetail c on b.BillingHeaderID = c.BillingHeaderID

我想得到的结果是这样的:

ID_TrnsacHeader   |  ID_TransacDetail  | ProcessID  | Before  |  After
     1                       1               1          1          6
     1                       2               1          2          7

问题是我上面的查询结果是这样的:

ID_TrnsacHeader   |  ID_TransacDetail  | ProcessID  | Before  |  After
     1                       1               1          1          6
     1                       2               1          2          6
     1                       1               1          1          7
     1                       2               1          2          7

我的目标是显示表TransactionDetail上的BillingDetailID和我在“After”之后调用的表格BillingDetail上的BillingDetailID之间的差异。 有人可以给我一个指示吗?

提前致谢

2 个答案:

答案 0 :(得分:1)

试试这个.......

select
    b.ID as ID_TransacHeader,
    a.ID as ID_TransacDetail,
    b.ProcessID
    ,a.BillingDetailID as Before
    ,c.BillingDetailID as After
from TransactionDetail a
inner join TransactionHeader b on a.ProcessID = b.ProcessID
inner join billingdetail c on b.BillingHeaderID = c.BillingHeaderID and a.billingdetailid = c.billingdetailid

答案 1 :(得分:0)

要连接两个或多个表,此示例可能会对您有所帮助:

select *
from
    tableA a
        inner join
    tableB b
        on a.common = b.common
        inner join 
    TableC c
        on b.common = c.common