加入SQL查询问题?

时间:2010-09-21 00:58:26

标签: sql mysql sql-server

首先选择声明:

SELECT
dbo.FG_FILLIN.PartNumber,
dbo.DropshipPackinglist.Shiplist_Qty,
dbo.DropshipPackinglist.Quantity
FROM   dbo.FG_FILLIN INNER JOIN
       dbo.DropshipPackinglist ON 
       dbo.FG_FILLIN.PartNumber = dbo.DropshipPackinglist.PartNumber
WHERE  (dbo.FG_FILLIN.Batch = 'CIP_HK_6')
GROUP BY 
dbo.FG_FILLIN.Batch,
dbo.FG_FILLIN.PartNumber,
dbo.FG_FILLIN.ItemNumber,
dbo.DropshipPackinglist.Shiplist_Qty,
dbo.DropshipPackinglist.Quantity

结果:

PartNumber  Shiplist_Qty    Quantity
P02-070161-00111-C100   6   3
P02-070161-10111-C100   6   3

第二名:

SELECT PartNumber,COUNT(Batch) AS Created
FROM         dbo.FG_FILLIN
WHERE Batch='CIP_HK_6'
GROUP BY Batch,PartNumber

结果:

PartNumber  Created
P02-070161-00111-C100   3
P02-070161-10111-C100   1

加入这两个查询我不能显示这一个:结果需要

PartNumber  Shiplist_Qty    Quantity  Created
P02-070161-00111-C100   6   3            3
P02-070161-10111-C100   6   3            1

它始终显示:当我添加Count(dbo.FG_FILLIN.Batch) as Created

PartNumber  Shiplist_Qty    Quantity  Created
P02-070161-00111-C100   6   3            6
P02-070161-10111-C100   6   3            2

任何建议。?谢谢你!

1 个答案:

答案 0 :(得分:2)

使用子选择:

   SELECT f.PartNumber,
          dpl.Shiplist_Qty,
          dpl.Quantity,
          (SELECT COUNT(Batch) AS Created
             FROM dbo.FG_FILLIN x
            WHERE x.batch = f.batch
              AND x.partnumber = f.partnumber
         GROUP BY Batch, PartNumber) AS created
     FROM dbo.FG_FILLIN f
    JOIN dbo.DropshipPackinglist dpl ON dpl.partnumber = f.partnumber
   WHERE f.Batch = 'CIP_HK_6'
GROUP BY f.Batch, f.PartNumber, f.ItemNumber, dpl.Shiplist_Qty, dpl.Quantity

使用JOIN到派生表/内联视图

   SELECT f.PartNumber,
          dpl.Shiplist_Qty,
          dpl.Quantity,
          x.created
     FROM dbo.FG_FILLIN f
     JOIN dbo.DropshipPackinglist dpl ON dpl.partnumber = f.partnumber
LEFT JOIN (SELECT t.partnumber,
                  t.batch,
                  COUNT(Batch) AS Created
             FROM dbo.FG_FILLIN t
         GROUP BY Batch, PartNumber) x ON x.partnumber = f.partnumber
                                      AND x.batch = f.batch
    WHERE f.Batch = 'CIP_HK_6'
 GROUP BY f.Batch, f.PartNumber, f.ItemNumber, dpl.Shiplist_Qty, dpl.Quantity

如果您只想查看具有created值的部分,请将“LEFT JOIN”更改为“JOIN”。