prograshid
prograshid

Reputation: 927

How to count most consecutive occurrences of a value in a Column in SQL Server

I have a table Attendance in my database.

Date       | Present
------------------------
20/11/2013 |  Y
21/11/2013 |  Y
22/11/2013 |  N
23/11/2013 |  Y
24/11/2013 |  Y
25/11/2013 |  Y
26/11/2013 |  Y
27/11/2013 |  N
28/11/2013 |  Y

I want to count the most consecutive occurrence of a value Y or N.

For example in the above table Y occurs 2, 4 & 1 times. So I want 4 as my result. How to achieve this in SQL Server?

Any help will be appreciated.

Upvotes: 2

Views: 2396

Answers (2)

praveen
praveen

Reputation: 12271

Try this:-

The difference between the consecutive date will remain constant

   Select max(Sequence)
  from 
  (
   select present ,count(*) as Sequence,
         min(date) as MinDt, max(date) as MaxDt
         from (
                select t.Present,t.Date,
                    dateadd(day,
                              -(row_number() over (partition by present order by date))
                               ,date 
                          ) as grp
              from Table1 t
            ) t
  group by present, grp
  )a
   where Present ='Y'

SQL FIDDLE

Upvotes: 4

Hart CO
Hart CO

Reputation: 34774

You can do this with a recursive CTE:

;WITH cte AS (SELECT Date,Present,ROW_NUMBER() OVER(ORDER BY Date) RN
              FROM Table1)
     ,cte2 AS (SELECT Date,Present,RN,ct = 1 
               FROM cte
               WHERE RN = 1
               UNION ALL
               SELECT a.Date,a.Present,a.RN,ct = CASE WHEN a.Present = b.Present THEN ct + 1 ELSE 1 END
               FROM cte a
               JOIN cte2 b
                 ON a.RN = b.RN+1)
SELECT TOP 1 *
FROM cte2
ORDER BY CT DESC

Demo: SQL Fiddle

Note, the date's in the demo got altered due to the format you posted the dates in your question.

Upvotes: 3

Related Questions