2014-01-31 220 views
2

我在我的數據庫中有一個表Attendance如何統計SQL Server中列中某個值的連續出現次數

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 

我想算一筆價值YN的最連貫的發生。

例如在上表Y發生2,4 & 1次。所以我想我的結果是。 如何在SQL Server中實現這一點?

任何幫助將不勝感激。

+0

哪個版本的SQL Server您使用常數? –

+0

@ astander-'SQL Server 2008' – prograshid

+0

你想怎麼做?在StoredProc/UDF或只是TSQL。 –

回答

4

試試這個: -

連續日期之間的差異仍將

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

3

您可以用遞歸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 

演示:SQL Fiddle

注意,日期在演示得到了改變,導致對您發佈的日期在你的問題的格式。

+1

您擊敗了我..完成了:-) –

+1

+1。感謝這就是我想要的:) – prograshid

相關問題