Left将一个表连接到一组内连接表中

时间:2014-04-16 07:49:03

标签: sql database ms-access relationship

抱歉我的英语不好,希望我能很好地解释我的问题。 我有如下SQL:

    SELECT tbCustomer.fKodeSales, 
           tbBarang.fKategori, 
           SUM(tbKanvasJualM.fTotal) AS SumTotal, 
           SUM(tbBarang.fIsi) AS SumIsi,
           SUM(tbKanvasJualDet.fQty) AS SumQty
      FROM (           tbCustomer 
             INNER JOIN tbKanvasJualM ON tbCustomer.fKodeCust =tbKanvasJualM.fKodeCust
           ) 
INNER JOIN (           tbBarang 
            INNER JOIN tbKanvasJualDet ON tbBarang.fKodeBrg = tbKanvasJualDet.fKodeBrg) 
        ON tbKanvasJualM.fNoKanvasJual = tbKanvasJualDet.fNoKanvasJual
  GROUP BY tbCustomer.fKodeSales, tbBarang.fKategori;

结果如下:

fKodeSales  |fKategori  |SumTotal   |SumIsi |SumQty 

ACONG       |DEPAN      |$170,000.00    |500    |10 

ACONG       |HLG        |$1,500,000.00  |2  |3

ACONG       |LAIN2      |$252,400.00    |4200   |220 

ALIANGPB    |DEPAN      |$467,000.00    |1100   |110 

ALIANGPB    |HLG        |$10,160,000.00 |1  |20 

ALIANGPB    |LAIN2      |$10,160,000.00 |1000   |100

现在我想从另一个表(tbRefund)添加列,该表保存退款项目的数据,而不是所有项目都退款。 比如,名为SumRefund的列

我尝试这个SQL但失败了,请帮帮我:

    SELECT tbCustomer.fKodeSales, 
           tbBarang.fKategori, 
           SUM(tbKanvasJualM.fTotal) AS SumTotal, 
           SUM(tbBarang.fIsi) AS SumIsi, 
           SUM(tbKanvasJualDet.fQty) AS SumQty , 
           SUM(tbReturJDet.fQty)
      FROM (           tbCustomer 
            INNER JOIN tbKanvasJualM ON tbCustomer.fKodeCust = tbKanvasJualM.fKodeCust)
INNER JOIN (           tbBarang 
            INNER JOIN tbKanvasJualDet ON tbBarang.fKodeBrg = tbKanvasJualDet.fKodeBrg)
        ON tbKanvasJualM.fNoKanvasJual = tbKanvasJualDet.fNoKanvasJual
 LEFT JOIN tbReturJDet 
        ON tbReturJDet.fKodeBrg=tbKanvasJualDet.fKodeBrg
  GROUP BY tbCustomer.fKodeSales, tbBarang.fKategori

我知道上面的代码不起作用,我怎么能纠正这个?

1 个答案:

答案 0 :(得分:0)

试试这个

SELECT 
tbCustomer.fKodeSales, 
tbBarang.fKategori, 
Sum(tbKanvasJualM.fTotal) AS SumTotal, 
Sum(tbBarang.fIsi) AS SumIsi, 
Sum(tbKanvasJualDet.fQty) AS SumQty, 
SUM(tbReturJDet.fQty)
FROM 
tbCustomer 
INNER JOIN tbKanvasJualM ON tbCustomer.fKodeCust = tbKanvasJualM.fKodeCust
INNER JOIN tbKanvasJualDet ON tbKanvasJualM.fNoKanvasJual = tbKanvasJualDet.fNoKanvasJual
INNER JOIN tbBarang  ON tbBarang.fKodeBrg = tbKanvasJualDet.fKodeBrg 
LEFT JOIN tbReturJDet ON tbReturJDet.fKodeBrg=tbKanvasJualDet.fKodeBrg
GROUP BY tbCustomer.fKodeSales, tbBarang.fKategori