简体   繁体   中英

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM