2014-09-30 22 views
0

我有一個像獲得連續5休假DB

staff_id | att_date  | status 

    1   2014-09-04  A 
    1   2014-09-05  P 
    1   2014-09-07  A 
    1   2014-09-08  A 
    1   2014-09-10  A 
    1   2014-09-11  A 
    1   2014-09-12  A   
    2   2014-09-04  P 
    3   2014-09-05  P 
    4   2014-09-06  P 
    2   2014-09-07  A 
    3   2014-09-08  P 

表我想誰了工作人員繼續5片葉。例如工作人員1繼續5次離開。我試過這個查詢。但是,它會列出即使工作人員花了5片葉不考慮繼續留

SELECT staff_id,count(*) 
FROM my_table 
WHERE status = 'A' 
GROUP BY staff_id HAVING count(*)>4 
+0

你有該表的主鍵? – Mihai 2014-09-30 10:25:56

+0

是的,我有主表上的主鍵 – Shafeeque 2014-09-30 10:34:20

回答

1

您可以使用排名查詢使用用戶定義變量爲每個staff_id組的每個重複狀態分配一個相同的等級,並在外部查詢中檢查計數

select staff_id,status,row_num 
from (
select *, 
@r:= case when @g = staff_id 
    then 
     case when @s <> `status` then @r + 1 else @r end 
     else @r + 1 
     end row_num, 
@g:= staff_id, 
@s:= status 
from my_table m 
cross join(select @g:=null,@r:=0,@s:=null) t 
order by staff_id,att_date,status 
) t1 
where status = 'A' 
group by staff_id 
having count(*) >= 5 

Demo

Another demo with changed data

編輯連續幾天

select staff_id,status,row_num 
from (
select *, 
@r:= case when @g = staff_id 
    then 
     case when @s <> `status` then @r + 1 else @r end 
     else @r + 1 
     end row_num, 
@g:= staff_id, 
@s:= status 
from my_table m 
cross join(select @g:=null,@r:=0,@s:=null) t 
where 
    case when @d is null then 1 else 
    DATEDIFF(att_date, @d) = 1 
    end 
order by staff_id,att_date,status 
) t1 
where status = 'A' 
group by staff_id 
having count(*) >= 5 

Demo for old data set

Demo for updated data set

+0

感謝您的回答,但未按預期工作。將第三個狀態更改爲P並且計數(*)> = 4.它不會繼續使用日期 – Shafeeque 2014-09-30 11:51:29

+0

@Shafeeq是此查詢將查找連續狀態A它不適用於連續日期 – 2014-09-30 11:53:54

+0

@Shafeeq在我的答案中也是'> = 5' not 4 ['See See demo'](http://sqlfiddle.com/#!2/231937/1) – 2014-09-30 11:56:10

0

您需要另一個變量來計算連續幾天

SELECT staffid ,status FROM 
(SELECT staffid,status, 
    CASE WHEN [email protected]_ci+INTERVAL 1 DAY THEN @n ELSE @n:[email protected]+1 END AS g, 
    @last_ci := att_date As att_date 
    FROM 
    t, (SELECT @n:=0) r 
ORDER BY staffid,att_date)x 
GROUP BY 
staffid,g 
HAVING SUM(status='A')>4 
AND COUNT(DISTINCT g)=1 

FIDDLE

+0

Im有點困惑att_date字段?你能否更新你的回答 – Shafeeque 2014-09-30 10:39:39

+0

它沒有按預期工作。我已更新我的問題 – Shafeeque 2014-09-30 12:00:45