Sql存储过程结合了类似材料和添加长度

时间:2017-12-26 20:57:40

标签: sql stored-procedures

我有一个SQL存储过程,它查看SQL表,然后给我材料及其长度。我想要的是查询结果只显示材料1次,并将所有长度添加到其材料中。我包括存储过程和我得到的结果的快照。

ALTER PROCEDURE [dbo].[MaterialLengthByMachine] 
    -- Add the parameters for the stored procedure here
    @Machine char (20) = 0
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    -- Insert statements for procedure here
    DECLARE @root hierarchyID;

    SELECT @root= Node
    FROM dbo.BOM
    WHERE BOM.PartNo=@Machine

    SELECT dbo.Components.Material, dbo.Components.[Length]
    FROM
            dbo.Components AS ParentComponents INNER JOIN
            dbo.BOM AS ParentBOM ON ParentComponents.PartNo = ParentBOM.PartNo INNER JOIN
            dbo.BOM AS PartBOM INNER JOIN
            dbo.Components ON PartBOM.PartNo = dbo.Components.PartNo ON ParentBOM.Node = PartBOM.Node.GetAncestor(1)

    WHERE 

         (PartBOM.Node.GetAncestor(PartBOM.Node.GetLevel() -1) = @root)

   GROUP BY dbo.Components.Material, dbo.Components.[Length]

END

以下是我得到的结果,例如我希望16-4电缆仅列出1次,但所有16-4长度要加在一起,总长度为1。

enter image description here

1 个答案:

答案 0 :(得分:0)

如果我理解正确,你会期待SUM长度。因此,在您的选择中添加SUM()关键字:dbo.Components.[Length]SUM(dbo.Components.[Length])

然后您还需要删除GROUP BY dbo.Components.[Length],因为它会按每个长度分组,而您只想按材质分组。

应该如下所示:

SELECT dbo.Components.Material, SUM(dbo.Components.[Length])
FROM
        dbo.Components AS ParentComponents INNER JOIN
        dbo.BOM AS ParentBOM ON ParentComponents.PartNo = ParentBOM.PartNo INNER JOIN
        dbo.BOM AS PartBOM INNER JOIN
        dbo.Components ON PartBOM.PartNo = dbo.Components.PartNo ON ParentBOM.Node = PartBOM.Node.GetAncestor(1)

WHERE 

     (PartBOM.Node.GetAncestor(PartBOM.Node.GetLevel() -1) = @root)

GROUP BY dbo.Components.Material