以下是数据:
empID Date Type
----- -------- ----
1 1/1/2012 u
1 1/2/2012 u
1 1/3/2012 u
1 2/2/2012 u
4 1/1/2012 u
4 1/3/2012 u
4 1/4/2012 u
4 1/6/2012 u
会回来:
empID count
----- -----
1 2
4 3
当两个日期“在一起”时,它们计为一次出现,如果日期被分开,则它们计为两次出现。这是为了跟踪员工的出勤情况......如何将SQL语句看起来按“合并”日期进行分组,并将它们计为1 ...我真的很难理解逻辑。
答案 0 :(得分:1)
SELECT
empID
, COUNT(*) AS cnt
FROM
tableX AS x
WHERE
NOT EXISTS
( SELECT *
FROM tableX AS y
WHERE y.empID = x.empID
AND DATEADD ("d", -1, x.[Date]) = y.[Date]
)
GROUP BY
empID ;
答案 1 :(得分:0)
试试这个:
;WITH CTE as
(select *,ROW_NUMBER() over (partition by empID order by date) as rn from test2 t1)
select empID,COUNT(*) as count
from CTE c1
where isnull((DATEDIFF(day,(select date from CTE where c1.rn=rn+1 and empID=c1.empID ),c1.date)),0) <> 1
group by empID