获取每个关系的最高价值

时间:2018-12-12 22:19:39

标签: sql sql-server tsql

我有项目表,ProjectDesign表和设计表

因此,每个项目都有多个设计,它们与ProjectDesign表相关

项目表

+------------+----------+
| ProjectKey |   Name   |
+------------+----------+
|          1 | Project1 |
|          2 | Project2 |
|          3 | Project3 |
+------------+----------+

ProjectDesign表

+------------+-----------+
| ProjectKey | DesignKey |
+------------+-----------+
|          1 |         1 |
|          2 |         2 |
|          3 |         3 |
|          1 |         4 |
|          1 |         5 |
+------------+-----------+

设计表

+-----------+------+
| DesignKey | Name |
+-----------+------+
|         1 | Key1 |
|         2 | Key2 |
|         3 | Key3 |
|         4 | Key4 |
|         5 | Key5 |
+-----------+------+

我要做的是选择每个项目的MAX designKey。我尝试为:

SELECT MAX([PD].[DesignKey])
FROM [Project] AS [p]
INNER JOIN [ProjectDesign] AS [PD] ON [PD].[ProjectKey] = [P].[ProjectKey]
INNER JOIN [Design] AS [D] ON [PD].[DesignKey] = [D].[DesignKey]

但是它只有一个值,它是最高的设计关键,但是我想要每个项目的最高设计关键。我该如何实现?

3 个答案:

答案 0 :(得分:1)

仅桥接表足以让您获得此

SELECT ProjectKey, max(DesignKey)
From ProjectDesign
Group by ProjectKey

答案 1 :(得分:1)

您可以简单地执行以下操作:

SELECT [p].ProjectKey, max([PD].[DesignKey])
FROM [Project] AS [p]
INNER JOIN [ProjectDesign] AS [PD] ON [PD].[ProjectKey] = [P].[ProjectKey]
INNER JOIN [Design] AS [D] ON [PD].[DesignKey] = [D].[DesignKey]
group by [p].ProjectKey;

答案 2 :(得分:0)

您可以使用GROUP BY或Windowing函数来执行此操作-这是使用windowing函数的方法:

SELECT MAX([PD].[DesignKey]) OVER (PARTITION BY PD.ProjectKey) AS MAX_BY_PROJECT
FROM [Project] AS [p]
INNER JOIN [ProjectDesign] AS [PD] ON [PD].[ProjectKey] = [P].[ProjectKey]
INNER JOIN [Design] AS [D] ON [PD].[DesignKey] = [D].[DesignKey]