我有2张桌子:
DesignGroup表:
+--------------------------------------+--------+
| DesignGroupId | Name |
+--------------------------------------+--------+
| 9D32C543-24EA-497E-918E-387C8A66BF1A | Group1 |
| 532C543E-24EA-497E-918E-387C8A66BF1A | Group2 |
+--------------------------------------+--------+
设计表:
+-----------+---------------+--------------------------------------+
| DesignKey | Name | DesignGroupId |
+-----------+---------------+--------------------------------------+
| 1 | Design | 9D32C543-24EA-497E-918E-387C8A66BF1A |
| 2 | Design | 9D32C543-24EA-497E-918E-387C8A66BF1A |
| 3 | AnotherDesign | 532C543E-24EA-497E-918E-387C8A66BF1A |
+-----------+---------------+--------------------------------------+
如您所见,多个设计可以具有相同的DesignGroupId,所以我进行如下查询:
DECLARE @DesignName VARCHAR(255) = 'Design'
SELECT
[D].[Name] AS [Display],
[D].[DesignKey] AS [Value]
FROM
[Design] AS [D]
JOIN
[DesignGroup] AS [DG] ON [D].[DesignGroupId] = [DG].[DesignGroupId]
GROUP BY
[D].[Name], [D].[DesignKey];
我的愿望结果是,每个DesignGroupId仅获得一个值[Display]和一个[Value],所以我的愿望结果是:
+---------------+-------+
| Display | Value |
+---------------+-------+
| Design | 1 |
| AnotherDesign | 3 |
+---------------+-------+
但是我得到每个DesignKey的结果,如:
+---------------+-------+
| Display | Value |
+---------------+-------+
| Design | 1 |
| Design | 2 |
| AnotherDesign | 3 |
+---------------+-------+
我该如何解决?问候
答案 0 :(得分:1)
我不明白为什么需要加入表格。
您想要的结果仅取决于表[Design]
中的数据。
因此GROUP BY [Name]
并获得[DesignKey]
的最小值:
SELECT
[Name] AS [Display],
MIN([DesignKey]) AS [Value]
FROM [Design]
GROUP BY [Name];
但是如果表中的DesignGroupId
只有一个值,那就没问题了。
其他DesignGroupId
所需要的结果是什么?
也许GROUP BY [DesignGroupId], [Name]
:
SELECT
[DesignGroupId],
[Name] AS [Display],
MIN([DesignKey]) AS [Value]
FROM [Design]
GROUP BY [DesignGroupId], [Name];
答案 1 :(得分:0)
您的目标是获取每个名称(显示)和组的最小DesignKey值吗?您可以将结果包装到最小值外部查询中:
SELECT DISPLAY, MIN(VALUE) from (
SELECT
[D].[Name] AS [Display],
[D].[DesignKey] AS [Value]
FROM
[Design] AS [D]
JOIN
[DesignGroup] AS [DG] ON [D].[DesignGroupId] = [DG].[DesignGroupId]
GROUP BY
[D].[Name], [D].[DesignKey])
GROUP BY Display;