SQL命令组合字段中的行

时间:2012-07-09 21:05:33

标签: sql sql-server

我正在尝试将来自一个表的行与我在MS Server上的查询组合在服务器2008上。我相信这里已删除此代码。这几乎符合我的需求,但是它将序列号分组为SOPartsUsed但我需要它基于tblServiceOrders.ProjectKeyID进行分组。任何帮助将不胜感激我不太了解SQL。我将在下面详细解释我想要完成的任务。

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

我有一个带有序列号的表,一个表,其中包含用于服务订单和服务订单表的部件。

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

我想要什么 ITEMID ProjectKeyID的SerialNumber
1 PJ366 1444,1555,1666,1999,1888

我得到了什么 ITEMID ProjectKeyID的SerialNumber
1个PJ366 1444,1555,1666
1 PJ366 1999,1888

我正在尝试通过tblServiceOrders中找到的ProjectKeyID对序列号和项ID进行分组。现在上面的查询有效,但是它在TblSOPartsUsed上对ItemID进行分组,并希望在ProjectKeyID上进行分组。

感谢您的帮助。

2 个答案:

答案 0 :(得分:0)

试试这个

SELECT        
p1.ItemID, p2.ProjectKeyID,D.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.ItemID = p1.ItemID
         ORDER BY SerialNumber FOR XML PATH(''), TYPE ).value('.', 'varchar(max)'), 1, 1, '')
) D (SerialNumbers)
WHERE        (p1.QuantityFilled > 0) AND (p2.ProjectKeyID = 'PJ366')
GROUP BY p1.ItemID, p2.ProjectKeyID, SerialNumbers 
ORDER BY p1.ItemID

答案 1 :(得分:0)

SELECT  itemID ,
    ProjectKeyID ,
    ( SELECT    SerialNumber + ', ' AS 'data()'
      FROM      dbo.tblSOPartsUsed u
                JOIN tblSerialNumbers nbr ON u.SOPartsUsed = nbr.FKSOPartsUsed
      WHERE     SONumber IN ( SELECT    SOnumber
                              FROM      dbo.tblServiceOrders
                              WHERE     ProjectKeyID = tso.ProjectKeyId )
                AND itemID = tso.itemID
    FOR
      XML PATH('')
    )
FROM    ( SELECT DISTINCT
                c.itemID ,
                ProjectKeyId
      FROM      dbo.tblServiceOrders a
                JOIN dbo.tblSOPartsUsed b ON a.SOnumber = b.SONumber
                JOIN dbo.tblSerialNumbers c ON b.SOPartsUsed = c.FKSOPartsUsed
    ) tso

我不认为我完全理解你想用itemID完成什么 - 样本中只有一个不同的值会让你很难验证结果 - 但这可能会让你更接近