按组多个列SQL Server分组后选择1行

时间:2017-09-05 21:23:19

标签: sql sql-server

我有一个包含id,版本,时间戳的表格,我需要为每个id超过1的版本获取最新版本。

例如

123 1.5 2015-03-28 08:21:04.563
123 1.4 2015-02-28 08:21:04.563
234 1.5 2015-06-28 08:21:04.563
234 1.4 2015-05-28 08:21:04.563
234 1.3 2015-04-28 08:21:04.563
345 1.5 2015-01-28 08:21:04.563

在上面的数据中,id 123和234有1个以上的版本。我需要获取max(时间戳)以及id和版本

输出

123 1.5 2015-03-28 08:21:04.563
234 1.5 2015-06-28 08:21:04.563

我有以下sql,它会为每个id提供1行,但是我需要排除只有1个版本的ID。

 ;with versions as
(
    select  id, 
            version, 
            row_no = row_number() over (partition by id order by max(dt_create) desc), 
            dt_create = max(dt_create)
    from table_name
    group by id, version
)
select id,version,row_no, dt_create
from versions
where row_no=1
order by id

3 个答案:

答案 0 :(得分:2)

你不需要row_number中的聚合。此外,您还希望使用IN子句来限制您声明的ID。

作为旁注,row_number比在其他答案中使用的聚合快得多。在原始查询中很好的选择。

 ;with versions as
(
    select  id, 
            version, 
            row_no = row_number() over (partition by id order by dt_create desc) 
    from table_name
)
select id,version,row_no, dt_create
from versions
where row_no=1 and id in (select id from versions where row_no > 1)
order by id

答案 1 :(得分:1)

这应该这样做:

    ;with mycte as (
select 123 as ID, 1.5 as version, '2015-03-28 08:21:04.563' as timestamp
union all 
select 123, 1.4, '2015-02-28 08:21:04.563'
union all 
select 234, 1.5, '2015-06-28 08:21:04.563'
union all 
select 234, 1.4, '2015-05-28 08:21:04.563'
union all 
select 234, 1.3, '2015-04-28 08:21:04.563'
union all 
select 345, 1.5, '2015-01-28 08:21:04.563'
)

Select ID
, max(version) as version
, max(timestamp) as timestamp
,count(*) as total
 from mycte
 group by ID
 having count(*) >1

答案 2 :(得分:0)

您的查询已结束。添加HAVING子句以排除只有一个版本的记录

;with versions as
(
    select  id, 
            version, 
            row_no = row_number() over (partition by id order by max(dt_create) desc), 
            dt_create = max(dt_create)
    from table_name
    group by id, version
    having COUNT(*) > 1
)
select id,version,row_no, dt_create
from versions
where row_no=1
order by id