SQL Server - 在列上使用MAX()值选择一行

时间:2016-06-18 07:55:55

标签: sql sql-server

这是我的表格表结构

id  | Name          | Date          | VersionID
----+---------------+---------------+-------------------------------------
1   |  Item 1       | 10/15/2012    | F8883CA4-3603-476D-BA33-1BBB6B87A79F
1   |  Item 1       | 11/06/2012    | AA22DA27-87D1-42EC-96F6-A4846A45DF6B
1   |  Item 1       | 11/06/2018    | AA22DA27-87D1-42EC-96F6-A4846A45DF6B
2   |  Item 2       | 11/06/2015    | F8883CA4-3603-476D-BA33-1BBB6B87A79F
2   |  Item 2       | 12/15/2012    | AA22DA27-87D1-42EC-96F6-A4846A45DF6B
2   |  Item 2       | 1/19/2013     | F8883CA4-3603-476D-BA33-1BBB6B87A79F

从这张表中,对于每个版本,我希望每个项目都有最大日期。

实施例

id  | Name          | Date          | VersionID
----+---------------+---------------+-------------------------------------
1   |  Item 1       | 10/15/2012    | F8883CA4-3603-476D-BA33-1BBB6B87A79F
1   |  Item 1       | 11/06/2018    | AA22DA27-87D1-42EC-96F6-A4846A45DF6B
2   |  Item 2       | 11/06/2015    | F8883CA4-3603-476D-BA33-1BBB6B87A79F
2   |  Item 2       | 12/15/2012    | AA22DA27-87D1-42EC-96F6-A4846A45DF6B

我尝试了rankdense_rank函数,但我尝试的逻辑并没有返回预期的结果。想法?

2 个答案:

答案 0 :(得分:3)

通常的方法是使用row_number

select id, name, date, versionid
from (select s.*,
             row_number() over (partition by id, version_id order by date desc) as seqnum
      from structure s
     ) s
where seqnum = 1;

答案 1 :(得分:0)

我们可以通过使用MAX条件和Co-相关子查询得到结果

DECLARE @Table1 TABLE 
    (id int, Name varchar(6), Date datetime, VersionID varchar(36))
;

INSERT INTO @Table1
    (id, Name, Date, VersionID)
VALUES
    (1, 'Item 1', '2012-10-15 05:30:00', 'F8883CA4-3603-476D-BA33-1BBB6B87A79F'),
    (1, 'Item 1', '2012-11-06 05:30:00', 'AA22DA27-87D1-42EC-96F6-A4846A45DF6B'),
    (1, 'Item 1', '2018-11-06 05:30:00', 'AA22DA27-87D1-42EC-96F6-A4846A45DF6B'),
    (2, 'Item 2', '2015-11-06 05:30:00', 'F8883CA4-3603-476D-BA33-1BBB6B87A79F'),
    (2, 'Item 2', '2012-12-15 05:30:00', 'AA22DA27-87D1-42EC-96F6-A4846A45DF6B'),
    (2, 'Item 2', '2013-01-19 05:30:00', 'F8883CA4-3603-476D-BA33-1BBB6B87A79F')
;

Select T.id,T.Name,TT.Dt,T.VersionID from @Table1 T
INNER JOIN (
select id,Name,MAX(Date)Dt,VersionID from @Table1 
GROUP BY id,Name,VersionID)TT
ON T.id = TT.id AND T.Date = TT.Dt