如何对连续日期范围内的数据进行分组

时间:2019-07-20 12:36:29

标签: sql ms-access

我有一张表格,我在其中输入每个员工的出勤情况,包括年假(代码:LAn)或临时假(代码:LCa)。

+-------+-----------+-----+
|  ID   |   Date    | Att |
+-------+-----------+-----+
|  9999 | 01-Jul-19 | LCa |
|  9999 | 02-Jul-19 | LCa |
|  9999 | 03-Jul-19 | LCa |
| 10000 | 15-Jul-19 | LAn |
| 10000 | 16-Jul-19 | LAn |
| 10000 | 17-Jul-19 | LAn |
| 10000 | 18-Jul-19 | LAn |
| 10000 | 19-Jul-19 | LAn |
|  9999 | 22-Jul-19 | LCa |
|  9999 | 23-Jul-19 | LCa |
|  9999 | 24-Jul-19 | LCa |
+-------+-----------+-----+

我正在使用MS Access 2016。

它与以下问题非常相似:enter image description here,但我想要MS Access中的解决方案。有人可以帮我吗?

我希望查询根据日期对数据进行分区,以便输出看起来像这样:

+-------+-----------+-----------+------+-----+
|  ID   | DateFrom  |  DateTo   | Days | Att |
+-------+-----------+-----------+------+-----+
|  9999 | 01-Jul-19 | 03-Jul-19 |    3 | LCa |
| 10000 | 15-Jul-19 | 19-Jul-19 |    5 | LAn |
|  9999 | 22-Jul-19 | 24-Jul-19 |    3 | LCa |
+-------+-----------+-----------+------+-----+

1 个答案:

答案 0 :(得分:3)

在MS Access中,您可以使用相关子查询来生成序列号。然后从日期中减去序号以标识组:

select id, min(date), max(date), att
from (select t.*,
             (select count(*)
              from t as t2
              where t2.id = t.id and
                    t2.date <= t.date
             ) as seqnum
      from t
     ) as t
group by id, att, dateadd("d", - seqnum, date)