简体   繁体   中英

Join SQL Query Problem?

First Select Statement:

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

Result :

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

2nd :

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

Result :

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

Joining this two Query I cant show this one: RESULT NEEDED

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

It always show : when i Add 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

Any Advice.? Thanks In Regards!

Using a subselect:

   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

Using a JOIN to a derived table/inline view

   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

Change "LEFT JOIN" to "JOIN" if you only want to see parts that have created values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM