获取最大数量取决于关系

时间:2019-04-02 20:20:14

标签: sql tsql

我有这个查询:

 SELECT
                   MAX([D].[DesignKey]) AS [DesignKey]
                   FROM [Project] AS [P]
                       INNER JOIN [DesignGroup] AS [DG] ON [P].[ProjectKey] = [DG].[ProjectKey]
                       INNER JOIN [Design] AS [D] ON [DG].[DesignGroupId] = [D].[DesignGroupId]
                   GROUP BY
                          [P].[ProjectKey]
                        , [D].[Name]
                        ORDER BY DesignKey

我的关系是:一个项目可以有多个DesignGroups,而一个Design可以有多个DesignGroups,但是一个设计不能有多个项目

我要选择的是每个DesignGroup的最大设计密钥号,我该如何实现?对于我的查询,它返回所有DesignKeys,它不在乎每个designGroup是否在最后。问候

2 个答案:

答案 0 :(得分:1)

这应该做您想要的:

SELECT [DG].[DesignGroupId], MAX([D].[DesignKey]) AS [DesignKey]
FROM [DesignGroup] [DG] JOIN
     [Design] [D]
     ON [DG].[DesignGroupId] = [D].[DesignGroupId]
GROUP BY [DG].[DesignGroupId];

请注意,PROJECT表不需要回答您的问题。

答案 1 :(得分:0)

对分组依据和选择使用DesignGroupId

SELECT
                  DesignGroupId, MAX([D].[DesignKey]) AS [DesignKey]
                   FROM [Project] AS [P]
                       INNER JOIN [DesignGroup] AS [DG] ON [P].[ProjectKey] = [DG].[ProjectKey]
                       INNER JOIN [Design] AS [D] ON [DG].[DesignGroupId] = [D].[DesignGroupId]
                   GROUP BY
                          DesignGroupId
                       ORDER BY DesignKey