I'm trying to understand how to combine queries when one of them returns more than one record.
This is an invoicing report where I want to pull in the Serial Numbers of products invoiced. I'll abbreviate the script as much as possible to clarify. Here is my script before adding the serials:
SELECT ARM.fcustno AS [Cust No]
, ARM.fbcompany AS [Cust Name]
, ARM.fcinvoice AS [Invoice No]
, ARM.fdgldate AS [Post Date]
, ARI.fitem AS [Item No]
, ARI.fprodcl AS [Prod Class]
, ARI.fshipkey AS [Qty Invoiced]
, ARI.fpartno AS [Part No]
, ARI.frev AS [Part Rev]
, ARI.FTOTPRICE AS [Net Invoiced]
, ARM.fsono AS [Sales No]
, SOM.fcusrchr2
FROM dbo.armast ARM
INNER JOIN dbo.aritem ARI ON ARM.FCINVOICE = ARI.FCINVOICE
INNER JOIN slcdpm SLC ON SLC.fcustno = ARM.fcustno
LEFT OUTER JOIN slcdpm_ext SLCE ON SLC.identity_column = SLCE.fkey_id
LEFT OUTER JOIN somast SOM ON SOM.fsono = ARM.fsono
This returns invoiced line items, their prices, and such. When I pull in the following:
SELECT ARM.fcustno AS [Cust No]
, ARM.fbcompany AS [Cust Name]
, ARM.fcinvoice AS [Invoice No]
, ARM.fdgldate AS [Post Date]
, ARI.fitem AS [Item No]
, ARI.fprodcl AS [Prod Class]
, ARI.fshipkey AS [Qty Invoiced]
, ARI.fpartno AS [Part No]
, ARI.frev AS [Part Rev]
, ARI.FTOTPRICE AS [Net Invoiced]
, ARM.fsono AS [Sales No]
, SOM.fcusrchr2
, LOTC.fcuseinlot
FROM dbo.armast ARM
INNER JOIN dbo.aritem ARI ON ARM.FCINVOICE = ARI.FCINVOICE
INNER JOIN slcdpm SLC ON SLC.fcustno = ARM.fcustno
LEFT OUTER JOIN slcdpm_ext SLCE ON SLC.identity_column = SLCE.fkey_id
LEFT OUTER JOIN somast SOM ON SOM.fsono = ARM.fsono
--** New stuff below: ******
LEFT OUTER JOIN ShItem SHI ON SHI.fShipNo + SHI.fItemNo = ARI.fShipKey
LEFT OUTER JOIN ShSrce ON ShSrce.fcShipNo = SHI.fShipNo
AND ShSrce.fcItemNo = SHI.fItemNo
LEFT OUTER JOIN QaLotC LOTC ON LOTC.fcUseInDoc = ShSrce.fcShipNo + ShSrce.fcItemNo + ShSrce.fcSrcItmNo
The problem is that there can be multiple SHSRCE records per invoice. What is the best way to handle this? Perhaps use a subquery to concatenate the LOTC.fcuseinlot field in order to return one corresponding value per record.
To clarify, the additional query returns more than 1 record per line item invoice because multiple serial number parts can be invoiced on one line item. Ideally, I'd like them to be concatenated like (NCC1701, R2D2, C3PO) etc. That's why I thought about using a subquery to concatenate them.