SQL 查询 select 具有不同主题的最新记录

SQL query to select the latest records with a distinct subject

我正在使用 SQL 服务器并有一个 table 设置如下:

| 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 |

我想 select 每个主题词的最新记录,因此要 return 编辑的记录是:

| 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

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

您可以使用 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 将 return 每条记录具有每个 subject 的最新 modified 日期。如果有两条或多条记录共享相同的 'latest' 日期,并且您想要 所有 这些记录 returned,那么您可以查看 RANK() window 函数。

使用 ROW_NUMBER 这变得非常简单。

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

您可以使用 rank window 函数只检索最新记录:

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