Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting how many times a boolean value changes in SQL Server

I have this table:

     [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

I need a query to count how many times the value changes.

For example:

    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
like image 897
Álvaro Ruiz Avatar asked Nov 09 '14 14:11

Álvaro Ruiz


People also ask

How do I count how many times a word appears in SQL?

T-SQL doesn't provide a built-in function to count the number of times a particular string appears within another string, so to find out how many times a word appears in a row, you have to build your own count function.

Can we use count (*)?

There sure is! As you've already learned, COUNT(*) will count all the rows in the table, including NULL values. On the other hand, COUNT(column name) will count all the rows in the specified column while excluding NULL values.

What is Count * or Count 1 in SQL?

With COUNT(1), there is a misconception that it counts records from the first column. What COUNT(1) really does is that it replaces all the records you get from query result with the value 1 and then counts the rows meaning it even replaces a NULL with 1 meaning it takes NULLs into consideration while counting.


2 Answers

You can do this with lag():

select count(*)
from (select t.*, lag(value) order by (sdate) as prev_value
      from table t
     ) t
where prev_value <> value ;
like image 192
Gordon Linoff Avatar answered Sep 23 '22 02:09

Gordon Linoff


This should work in earlier versions too..

;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 
like image 40
Pரதீப் Avatar answered Sep 25 '22 02:09

Pரதீப்