I am trying to combine rows from one table with my query in MS SQL on server 2008. I pulled this code off here I believe. This almost fits my needs but it is grouping the serial numbers off of SOPartsUsed but I need it to group based off tblServiceOrders.ProjectKeyID. Any help would be greatly appreciated I don’t know much about SQL. I will leave a more detailed explanation of what I am trying to accomplish below.
SELECT
p1.ItemID, SerialNumbers AS SerialNumber
FROM
tblSOPartsUsed p1 INNER JOIN
tblServiceOrders p2 ON p1.SONumber = p2.SONumber
CROSS APPLY
(SELECT
stuff
((SELECT ',' + p3.SerialNumber
FROM tblSerialNumbers p3
WHERE p3.FKSOPartsUsed = p1.SOPartsUsedKeyID
ORDER BY SerialNumber FOR XML PATH(''), TYPE ).value('.', 'varchar(max)'), 1, 1, '')
) D (SerialNumbers)
WHERE (p1.QuantityFilled > 0) AND (p2.ProjectKeyID = 385)
GROUP BY p1.ItemID, SerialNumbers, p2.ProjectKeyID
ORDER BY p1.ItemID
I have a table with serial numbers a table with parts used on a service order and a service order table.
tblSerialNumbers -> tblSOPartsUsed -> tblServiceOrders
tblSerialNumbers
itemID SerialNumber FKSOPartsUsed
1 1444 233
1 1555 234
1 1666 236
1 1999 237
1 1888 238
1 2222 239
1 2121 240
tblSOPartsUsed
itemID SOPartsUsed SONumber QuantityFilled
1 233 SO544 5
1 234 SO544 7
1 236 SO544 7
1 237 SO577 7
1 238 SO577 7
1 239 SO581 7
1 240 SO580 7
tblServiceOrders
SOnumber ProjectKeyID
SO544 PJ366
SO577 PJ366
SO580 PJ111
SO581 PJ111
What I would like
itemID ProjectKeyID SerialNumber
1 PJ366 1444,1555,1666,1999,1888
What I get
itemID ProjectKeyID SerialNumber
1 PJ366 1444,1555,1666
1 PJ366 1999,1888
I am trying to group serial numbers and item id’s by ProjectKeyID found in tblServiceOrders. Right now the query above works but it is grouping ItemID’s on the tblSOPartsUsed and want to group on ProjectKeyID.
Thanks for any help.
I don’t think I totally understand what you’re trying to accomplish with itemID – having only one distinct value in the sample makes it hard to verify results – but this might get you closer