查找连续周计数

时间:2018-04-19 14:48:02

标签: sql sql-server

我有下表

PLAN_DATA
[username],[workdate],[pid]

我想找到连续几周,其中填充PID = 12。 我正在尝试以下查询以获得预期结果

enter image description here

select username,DATEPART(w,workdate),DATEPART(m,workdate),pid 
from plan_data where username='peter' and YEAR(workdate)=2018 
and pid=12
group by username,DATEPART(w,workdate),DATEPART(m,workdate),pid

该表将包含52周不同PID的数据。 我希望得到像PIDs = 12这样的上述格式的结果,即连续的周数超过3次。 连续几周填充的PID 12必须跟踪

1 个答案:

答案 0 :(得分:1)

您想将连续周数组合在一起吗?

你可以使用row_number和week之间区别的技巧,如下所示:

select *, w - RN from (
    select *, row_number() over (partition by m order by w asc) as RN
    from(
        select username,DATEPART(w,workdate) as w,DATEPART(m,workdate) as m,pid 
        from plan_data where username='peter' and YEAR(workdate)=2018 
        and pid=12
        group by username,DATEPART(w,workdate),DATEPART(m,workdate),pid
    ) X
) Y

根据您的目的,根据w-RN,min / max等对该数据应用分组。