如何对这些数据进行分组,以便从每个组中提取特定的行

时间:2017-02-09 17:19:37

标签: sql sql-server-2008 group-by

我有如下所示的数据集。由此,我想从每个组中选择PersonID状态已更改为与上一个状态不同的状态的第一行。

例如,从这个数据集中,我想要行1,4,7和11 对此有何帮助?
如果我做GROUPBY,它只会将所有新的和所有待定的2个组合在一起。

PersonID    Status  WhenChanged
101         New     27/01/2017 15:27
101         New     27/01/2017 16:40
101         New     27/01/2017 16:40
101         Pending 27/01/2017 16:40
101         Pending 27/01/2017 16:40
101         Pending 27/01/2017 16:40
101         New     31/01/2017 09:14
101         New     31/01/2017 10:02
101         New     31/01/2017 10:03
101         New     31/01/2017 10:05
101         Pending 03/02/2017 14:29
101         Pending 03/02/2017 14:29

1 个答案:

答案 0 :(得分:0)

这里有一个...使用CTE。排序已关闭,因为您使用的日期是varchar格式或显示如此。你可以将它转换成相同的,这样可以正常工作。

Rplot001.jpeg

SQL Server 2008和早期版本

declare @table table (PersonID int, Status varchar(16), WhenChanged varchar(64))
insert into @table values
(101,'New','27/01/2017 15:27'),
(101,'New','27/01/2017 16:40'),
(101,'New','27/01/2017 16:40'),
(101,'Pending','27/01/2017 16:40'),
(101,'Pending','27/01/2017 16:40'),
(101,'Pending','27/01/2017 16:40'),
(101,'New','31/01/2017 09:14'),
(101,'New','31/01/2017 10:02'),
(101,'New','31/01/2017 10:03'),
(101,'New','31/01/2017 10:05'),
(101,'Pending','03/02/2017 14:29'),
(101,'Pending','03/02/2017 14:29')

;with cte as(
    select
        PersonID,
        Status,
        WhenChanged,
        case when lag(Status) over (partition by PersonID order by convert(datetime,WhenChanged,103)) <> Status then 1 else 0 end as d
    from
        @table)



select top 1 *
from @table
union 
select  PersonID,
        Status,
        WhenChanged
from cte
where d=1
order by WhenChanged