SQL Server - Selecting periods without changes in data -


what trying select periods of time rest of data in table stable based on 1 column , check there change in second column value in period.

table:

create table #stable_periods ( [date]             date, [car_reg]          nvarchar(10), [internal_damages] int, [external_damages] int )  insert #stable_periods values  ('2015-08-19', 'abc123', 10, 10),         ('2015-08-18', 'abc123', 9, 10),         ('2015-08-17', 'abc123', 8, 9),         ('2015-08-16', 'abc123', 9, 9),         ('2015-08-15', 'abc123', 10, 10),         ('2015-08-14', 'abc123', 10, 10),         ('2015-08-19', 'abc456', 5, 3),         ('2015-08-18', 'abc456', 5, 4),         ('2015-08-17', 'abc456', 8, 4),         ('2015-08-16', 'abc456', 9, 4),         ('2015-08-15', 'abc456', 10, 10),         ('2015-01-01', 'abc123', 1, 1),         ('2015-01-01', 'abc456', null, null);  --select * #stable_periods -- unfortunately can’t post pictures yet point of how table looks 

what receive is

car_reg	  fromdate	todate	          external_damages    have internal damages changed in period?  abc123	  2015-08-18	2015-08-19	  10	              yes  abc123	  2015-08-16	2015-08-17	  9	              yes  abc123	  2015-08-14	2015-08-15	  10	              no  abc123	  2015-01-01	2015-01-01	  1	              no  abc456	  2015-08-19	2015-08-19	  3	              no  abc456	  2015-08-16	2015-08-18	  4	              yes  abc456	  2015-08-15	2015-08-15	  10	              no  abc456	  2015-01-01	2015-01-01	  null	              null

basically build period frames [external_damages] constant , check did [internal_damages] change in same period (doesn't matter how many times). spend lot of time trying afraid level of abstraction thinking in low... great see suggestions.

thanks,

bartosz

i believe form of islands problem.

here solution using row_number , group by:

sql fiddle

with cte as(     select *,         rn = dateadd(day, - row_number() over(partition car_reg, external_damages order [date]), [date])     #stable_periods ) select     car_reg,     fromdate = min([date]),     todate = max([date]) ,     external_damages,     change =             case                  when max(external_damages) null null                 when count(distinct internal_damages) > 1 'yes'                  else 'no'              end      cte c group car_reg, external_damages, rn order car_reg, todate desc 

Comments

Popular posts from this blog

html - Firefox flex bug applied to buttons? -

html - Missing border-right in select on Firefox -

python - build a suggestions list using fuzzywuzzy -