计算SQL Server中的先前连续行

Sho*_*hel 3 sql sql-server sql-server-2012

我有下面显示的出勤数据列表。现在,我正在尝试查找特定日期范围(2016年1月5日至2016年7月5日)的数据,其中包含“当前总列数”,“总当前列数”将根据之前的当前数据(P)计算得出。假设今天是2016年4月5日。如果一个人的状态为01,02,03,04'p',那么它将显示日期04-05-2016共4。

在此处输入图片说明

您能帮我从此结果集中找到总礼物吗?

Aja*_*707 6

您可以检查此示例,该示例具有计算先前总和值的逻辑。

declare @t table (employeeid int, datecol date, status varchar(2) )

insert into @t values (10001, '01-05-2016', 'P'),
(10001, '02-05-2016', 'P'),
(10001, '03-05-2016', 'P'),
(10001, '04-05-2016', 'P'),
(10001, '05-05-2016', 'A'),
(10001, '06-05-2016', 'P'),
(10001, '07-05-2016', 'P'),
(10001, '08-05-2016', 'L'),
(10002, '07-05-2016', 'P'),
(10002, '08-05-2016', 'L')

--select * from @t 

select * ,  
    SUM(case when status = 'P' then 1 else 0 end) OVER (PARTITION BY   employeeid ORDER BY employeeid, datecol
    ROWS BETWEEN UNBOUNDED PRECEDING 
      AND current row) 
from 
@t
Run Code Online (Sandbox Code Playgroud)

通过cte进行相同操作的另一种方式(在编写SQLSERVER2012时,此以下解决方案仅在Sqlserver 2012及更高版本中有效)

;with cte as
(
    select  employeeid , datecol , ROW_NUMBER() over(partition by employeeid order by employeeid, datecol) rowno
    from 
    @t where status = 'P'
)
select t.*, cte.rowno , 
    case when ( isnull(cte.rowno, 0) = 0) 
    then LAG(cte.rowno) OVER (ORDER BY t.employeeid, t.datecol) 
    else cte.rowno
    end LagValue 
from @t t left join cte on t.employeeid = cte.employeeid and t.datecol = cte.datecol
order by t.employeeid, t.datecol
Run Code Online (Sandbox Code Playgroud)