sql - How to group this data so I can pull out specific rows from each group -
i have dataset shown below. this, want select first row each group personid
s status has changed different status previous one.
for example, dataset, want rows 1, 4, 7 , 11.
on this?
if groupby
, lumps new , pending in 2 groups.
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
here's go @ it...using cte. ordering off because date used in varchar format or displayed such. can convert same , work fine.
declare @table table (personid int, status varchar(16), whenchanged varchar(64)) insert @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) on (partition personid order convert(datetime,whenchanged,103)) <> status 1 else 0 end d @table) select top 1 * @table union select personid, status, whenchanged cte d=1 order whenchanged
sql server 2008 , previous editions
declare @table table (personid int, status varchar(16), whenchanged varchar(64)) insert @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, convert(datetime,whenchanged,103) whenchanged, row_number() on (order personid, convert(datetime,whenchanged,103)) rn @table), cteresults as( select personid, status, whenchanged cte rn = 1 union select c.personid, c.status, c.whenchanged cte c inner join cte c2 on c2.rn = (c.rn -1) , c2.status <> c.status) select * cteresults order whenchanged
Comments
Post a Comment