1

这是数据:

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......我真的在逻辑上苦苦挣扎。

4

2 回答 2

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 ;
于 2012-08-13T17:32:54.347 回答
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 
于 2012-08-13T18:10:14.240 回答