仅按一列分组

时间:2019-03-20 23:00:25

标签: sql sql-server tsql

我有这样的查询:

SELECT
             [D].[Name]  AS [Display]
            , [D].[DesignKey] AS [Value]
             FROM [Design] AS [D]
                 INNER JOIN [DesignGroup] AS [DG] ON [D].[DesignGroupId] = [DG].[DesignGroupId]
                 INNER JOIN [DesignType] AS [DT] ON [DT].[DesignTypeGuid] = [D].[DesignTypeGuid]
             WHERE [DG].[ProjectKey] = 4202
                  AND [D].[IsDeleted] = 0
                  AND [D].[Name] != 'CACHE REESED SEQUENCE'
             GROUP BY
                    [D].[Name], [D].[DesignKey]

它返回的数据为:

+-------------------------------------------+------+
|                  Design                   |  |
+-------------------------------------------+------+
| Design                                    | 5279 |
| Design                                    | 5280 |
| new design test                           | 5287 |
| another design                            | 5288 |
| NO CACHE FOLIO SEQUENCE                   | 5289 |
| RESEED                                    | 5291 |
| RESEED 2                                  | 5292 |
| RESEED 2                                  | 5306 |
| RESEED 2                                  | 5307 |
| RESEED 2                                  | 5308 |
| RESEED 2                                  | 5309 |
| test copy customers from  design RESEED 2 | 5310 |
+-------------------------------------------+------+

我想知道如何将结果分组为1 [D]。[名称]我的意思是获取每个名称的第一个DesignKey并得到如下结果:

+-------------------------------------------+------+
|                  Design                   | 4684 |
+-------------------------------------------+------+
| new design test                           | 5287 |
| another design                            | 5288 |
| NO CACHE FOLIO SEQUENCE                   | 5289 |
| RESEED                                    | 5291 |
| RESEED 2                                  | 5292 |
| test copy customers from  design RESEED 2 | 5310 |
+-------------------------------------------+------+

我该如何实现?

1 个答案:

答案 0 :(得分:2)

您似乎想要聚合:

SELECT D.Name as Display, MIN(D.DesignKey) as value
FROM Design D JOIN
     DesignGroup DG
     ON D.[DesignGroupId] = DG.[DesignGroupId] JOIN
     DesignType DT
     ON DT.[DesignTypeGuid] = D.[DesignTypeGuid]
WHERE [DG].[ProjectKey] = 4202 AND
      [D].[IsDeleted] = 0 AND
      [D].[Name] <> 'CACHE REESED SEQUENCE'
GROUP BY D.Name;