链接多个表混淆

时间:2013-11-28 10:25:19

标签: sql jointable

我有以下表格。每个标题都有一个状态,下面有很多框。每个框包含多行,每行包含多行。这是我的疑问:

select 
    Header.all, 
    count(no of available boxes), 
    count(number of available received lines), 
    sum(line_table.qty), 
    sum(receivedline_table.qty) 

where 
    HeaderNo like %something%

Header_Table

[HeaderID]  [HeaderNo]  [Ref]   [StatusID]
-----------------
1   ||HNO1  ||Ref1  ||1
2   ||HNO2  ||Ref2  ||2

Header_status_Table

[HeaderStatusID]    [statusDesc]
-----------------
1   ||Desc1
2   ||Desc2
3   ||Desc3

Box_table

[BoxID] [HeaderID]  [BoxNo]
-----------------
1   ||1 ||BNo1
2   ||1 ||BNo2
3   ||2 ||BNo3

Line_table

[LineID]    [BoxID] [QTY]   [HeaderID]
-----------------
1   ||1 ||15    ||1

2   ||1 ||2 ||1

ReceivedLine_Table

[RecievedID]    [LineID]    [qty]
-----------------
1   ||1 ||5
2   ||1 ||10

我已经编写了以下脚本,但不幸的是它没有像我预期的那样工作。

SELECT H.ID, H.No, H.Ref1, H.Ref2, H.Ref3, HS.StatusDesc, sum(isnull(LR.ReceivedQty,0)) as ReceivedQTY, sum(isnull(L.OrderedQty,0)) as OrderedQTY, count(L.Lineid) as NoLines , count(B.BoxID) as NoBoxes
        FROM Header H 
        left outer JOIN HeaderStatus HS ON H.StatusID = HS.StatusID
        left join Box B on B.ID = H.ID
        left join Line L on L.BoxID = B.BoxID
        left join LineReceived LR on L.Lineid = LR.LineID
        where H.No like '%%'
        group by H.ID, H.No, HS.StatusDesc, H.Ref1, H.Ref2, H.Ref3

1 个答案:

答案 0 :(得分:0)

最后我解决了它,我只是在我的选择脚本中单独选择,数据没有被抛弃并且看起来很好 HS.statusdesc作为状态,                         (从ASNBox B中选择计数(B.ASNBoxID),其中B.ASNID = H.ASNID)作为NumberOfBoxes