2014-11-09 18 views
12

Ho questa tabella:contare quante volte un valore booleano valore cambia in SQL Server

 [SDate - DateTime]     [Value] - Represents a boolean 
    2010-11-16 10:10:00     1 
    2010-11-16 10:11:00     0 
    2010-11-16 10:12:00     1 
    2010-11-16 10:13:00     1 

Ho bisogno di una query per contare quante volte il valore cambia.

Ad esempio:

2010-11-16 10:10:00     0 
    2010-11-16 10:11:00     1 
    2010-11-16 10:12:00     0 
    2010-11-16 10:13:00     0 
    2010-11-16 10:14:00     1 
    2010-11-16 10:15:00     0 
    2010-11-16 10:16:00     1 
    ... 
             5 changes 

2010-11-16 10:10:00     0 
    2010-11-16 10:11:00     0 
    2010-11-16 10:12:00     0 
    2010-11-16 10:13:00     1 
    2010-11-16 10:14:00     1 
    2010-11-16 10:15:00     1 
    2010-11-16 10:16:00     1 
    ...          
             1 change 

risposta

8

È possibile farlo con lag():

select count(*) 
from (select t.*, lag(value) order by (sdate) as prev_value 
     from table t 
    ) t 
where prev_value <> value ; 
+1

ringrazio molto !, penso che sia OVER (ORDER BY (sdate)) –

1

pre-SQL Server Soluzione 2012:

declare @t table (sdate datetime, value int) 

insert into @t(sdate, value) 
values 
--('2010-11-16 10:10:00', 0), 
--('2010-11-16 10:11:00', 1), 
--('2010-11-16 10:12:00', 0), 
--('2010-11-16 10:13:00', 0), 
--('2010-11-16 10:14:00', 1), 
--('2010-11-16 10:15:00', 0), 
--('2010-11-16 10:16:00', 1) 
('2010-11-16 10:10:00', 0), 
('2010-11-16 10:11:00', 0), 
('2010-11-16 10:12:00', 0), 
('2010-11-16 10:13:00', 1), 
('2010-11-16 10:14:00', 1), 
('2010-11-16 10:15:00', 1), 
('2010-11-16 10:16:00', 1) 


;with t_with_seq as (
    select 
    t.*, 
    ROW_NUMBER() OVER(ORDER BY t.sdate asc) as seq 
    from @t t 
) 
select 
    COUNT(*) 
from t_with_seq r 
    inner join t_with_seq r_next on r_next.seq = r.seq + 1 
where r.value <> r_next.value 
2

Questo dovrebbe funzionare nelle versioni precedenti troppo ..

;WITH cte 
    AS (SELECT Row_number()OVER(ORDER BY sdates) rn,* 
     FROM <tablename>) 
SELECT Sum(CASE WHEN a.boolvalue = b.boolvalue THEN 0 ELSE 1 END) 
FROM cte a 
     JOIN cte b 
     ON a.rn = b.rn + 1 
Problemi correlati