如何根据条件对连续日期进行分组

时间:2018-03-15 11:36:15

标签: mysql psql

我想在某些条件的基础上连续日期组

我的查询是

WITH
  dates(date) AS (
    SELECT DISTINCT CAST(leave_date AS DATE),t.employee_id,up.display_value
    FROM hrms.t_employee_leave_request t left join hrms.t_lookup up on up.id=t.leave_status_id
  )
,
  groups AS (
    select
    employee_id,display_value,
      ROW_NUMBER() OVER (ORDER BY date) AS rn,
      date((date - ROW_NUMBER() OVER (ORDER BY date) * interval '1 day')) as grp,
      date
    FROM dates
  )
  SELECT
  employee_id,display_value,
  COUNT(*) AS consecutiveDates,
  MIN(date) AS minDate,
  MAX(date) AS maxDate
FROM groups
GROUP BY employee_id,grp,display_value
ORDER BY 1 DESC, 2 desc;

将表结果返回为

| empid | action | days | fromdate | todate |

| 1022 | PendingApproval | 3 | 2018-03-19 | 2018年3月22日|

| 1022 |已批准| 1 | 2018-03-20 |二零一八年三月二十零日|

但我希望数据如下所示

| empid | action | days | fromdate | todate |

| 1022 | PendingApproval | 1 | 2018-03-19 | 2018年3月19日|

| 1022 | PendingApproval | 2 | 2018-03-21 | 2018年3月22日|

| 1022 |已批准| 1 | 2018-03-20 |二零一八年三月二十零日|

请帮我解决

0 个答案:

没有答案