用于选择具有不同主题

时间:2015-06-01 19:39:38

标签: sql sql-server group-by subquery aggregate-functions

我使用的是SQL Server,并设置了如下表格:

| id | subject | content | moreContent | modified   |
| 1  | subj1   | aaaa    | aaaaaaaaaaa | 03/03/2015 |
| 2  | subj1   | bbbb    | aaaaaaaaaaa | 03/05/2015 |
| 3  | subj2   | cccc    | aaaaaaaaaaa | 03/03/2015 |
| 4  | subj1   | dddd    | aaaaaaaaaaa | 03/01/2015 |
| 5  | subj2   | eeee    | aaaaaaaaaaa | 07/02/2015 |

我想为每个主题标题选择最新记录,因此要返回的记录为:

| id | subject | content | moreContent | modified   |
| 2  | subj1   | bbbb    | aaaaaaaaaaa | 03/05/2015 |
| 3  | subj2   | cccc    | aaaaaaaaaaa | 03/03/2015 |


SELECT Subject, MAX(Modified) FROM [CareManagement].[dbo].[Careplans] GROUP BY Subject

我可以像上面那样进行查询,但我想保留所选行中的所有内容。要返回内容列,我需要应用聚合函数,或将它们添加到group by子句中,这不会给我所需的效果。 我还查看了嵌套查询但尚未找到成功的解决方案。如果有人能提供帮助那就太好了。

3 个答案:

答案 0 :(得分:3)

您可以使用ROW_NUMBER()

SELECT id, subject,  content, moreContent, modified
FROM (
   SELECT id, subject,  content, moreContent, modified,
          ROW_NUMBER() OVER (PARTITION BY subject 
                             ORDER BY modified DESC) AS rn
   FROM [CareManagement].[dbo].[Careplans] ) t
WHERE rn = 1

rn = 1将返回每modifiedsubject日期RANK()日期的每条记录。如果有两个或多个记录共享相同的'最新'日期并且您希望返回所有这些记录,然后您可以查看with myCTE as ( select id , Subject , content , morecontent , Modified , ROW_NUMBER() over (PARTITION BY [Subject] order by Modified desc) as RowNum from [CareManagement].[dbo].[Careplans] ) select id , Subject , content , morecontent , Modified from myCTE where RowNum = 1 窗口函数。

答案 1 :(得分:1)

使用ROW_NUMBER这变得非常简单。

runAllManagedModulesForAllRequests

答案 2 :(得分:1)

您可以使用rank窗口功能仅检索最新记录:

SELECT id, subject, content, moreContent, modified
FROM   (SELECT id, subject, content, moreContent, modified,
               RANK() OVER (PARTITION BY subject ORDER BY modified DESC) AS rk
        FROM   [CareManagement].[dbo].[Careplans]) t
WHERE  rk = 1