groupby鉴于sql返回聚合错误

时间:2016-08-25 16:20:41

标签: sql-server view group-by aggregate

我正在尝试使用此查询创建一个视图,如下所示:

SELECT        dbo.Lines.LineNumber, dbo.Lines.DocumentNumber, dbo.Joints.JointNumber, dbo.Joints.JointSize, dbo.Joints.ShopField, dbo.Joints.WPS, dbo.WeldDetails.StateStep2 AS WeldState, dbo.Welds.WeldNumber, 
                         dbo.FitUps.FitUpNumber, MAX(dbo.WeldDetails.Id) AS WeldDetailId, MAX(dbo.FitUpDetails.Id) AS FitupDetailId, dbo.Joints.Id AS JointId, dbo.Ends.Name, dbo.Joints.THK, dbo.FitUpDetails.StateStep2 AS FitupState,
                          dbo.Joints.Revision, dbo.Joints.Note
FROM            dbo.FitUps INNER JOIN
                         dbo.Welds INNER JOIN
                         dbo.Joints INNER JOIN
                         dbo.WeldDetails ON dbo.Joints.Id = dbo.WeldDetails.JointId INNER JOIN
                         dbo.FitUpDetails ON dbo.Joints.Id = dbo.FitUpDetails.JointId ON dbo.Welds.Id = dbo.WeldDetails.WeldId ON dbo.FitUps.Id = dbo.FitUpDetails.FitUpId INNER JOIN
                         dbo.Lines ON dbo.Joints.LineId = dbo.Lines.Id INNER JOIN
                         dbo.Ends ON dbo.Joints.EndId = dbo.Ends.Id
GROUP BY dbo.Joints.Id

但是当我想保存视图时,我收到此错误: enter image description here

以下是我数据的一部分: enter image description here

在我的视图中,每个联合ID都可以有多个fitupdetailidwelddetailid,我只想显示我的关节的fitupdetailidwelddetailid的最大值。

1 个答案:

答案 0 :(得分:1)

我使用比GUI吐出的更易读的连接结构重写了您的查询。这应该为您运行并修复您的错误。结果是否符合您的要求取决于您的数据。您可能还希望重新排序分组以按层次结构分组。但是所有这些列都需要以一种或另一种形式进行分组。

SELECT
    dbo.Lines.LineNumber, 
    dbo.Lines.DocumentNumber, 
    dbo.Joints.JointNumber, 
    dbo.Joints.JointSize, 
    dbo.Joints.ShopField, 
    dbo.Joints.WPS, 
    dbo.WeldDetails.StateStep2 AS WeldState, 
    dbo.Welds.WeldNumber, 
    dbo.FitUps.FitUpNumber, 
    MAX(dbo.WeldDetails.Id) AS WeldDetailId, 
    MAX(dbo.FitUpDetails.Id) AS FitupDetailId, 
    dbo.Joints.Id AS JointId, 
    dbo.Ends.Name, 
    dbo.Joints.THK, 
    dbo.FitUpDetails.StateStep2 AS FitupState,
    dbo.Joints.Revision, 
    dbo.Joints.Note
FROM
    dbo.FitUps 
    INNER JOIN dbo.FitUpDetails ON dbo.FitUps.Id = dbo.FitUpDetails.FitUpId 
    INNER JOIN dbo.Joints ON dbo.Joints.Id = dbo.FitUpDetails.JointId 
    INNER JOIN dbo.WeldDetails ON dbo.Joints.Id = dbo.WeldDetails.JointId
    INNER JOIN dbo.Welds ON dbo.Welds.Id = dbo.WeldDetails.WeldId
    INNER JOIN dbo.Lines ON dbo.Joints.LineId = dbo.Lines.Id 
    INNER JOIN dbo.Ends ON dbo.Joints.EndId = dbo.Ends.Id
GROUP BY
    dbo.Lines.LineNumber, 
    dbo.Lines.DocumentNumber, 
    dbo.Joints.JointNumber, 
    dbo.Joints.JointSize, 
    dbo.Joints.ShopField, 
    dbo.Joints.WPS, 
    dbo.WeldDetails.StateStep2,
    dbo.Welds.WeldNumber, 
    dbo.FitUps.FitUpNumber, 
    dbo.Joints.Id,
    dbo.Ends.Name, 
    dbo.Joints.THK, 
    dbo.FitUpDetails.StateStep2,
    dbo.Joints.Revision, 
    dbo.Joints.Note