sql:查找连续几天内给定字段具有不同字符串值的记录

gblwokeq  于 2021-07-26  发布在  Java
关注(0)|答案(2)|浏览(433)

我有下表,我需要找到两个连续的天有不同的状态为同一个人(天之间没有差距)。

name    date           status
-------------------------------
John    2020-06-01     submitted
John    2020-06-02     pending
John    2020-06-03     approved
John    2020-06-04     approved
Amy     2020-06-02     pending
Amy     2020-06-03     pending
Amy     2020-06-04     pending
Dan     2020-06-02     submitted
Dan     2020-06-03     approved
Dan     2020-06-04     approved
Mary    2020-06-03     submitted
Mary    2020-06-04     pending

输出如下:

name    date           status
-------------------------------
John    2020-06-01     submitted
John    2020-06-02     pending
John    2020-06-03     approved
Dan     2020-06-02     submitted
Dan     2020-06-03     approved
Mary    2020-06-03     submitted
Mary    2020-06-04     pending

目前,我导出了这个表,并编写了一个python代码来实现这一点。但是,我想知道,仅仅使用sql是否有可能实现这一点(我查看了sql:只检索其值已更改的记录,但由于 status 字段是字符串而不是数字)谢谢!

pkwftd7m

pkwftd7m1#

我将根据名称、连续天数和不同状态自动加入表:

SELECT a.name, a.date, a.status
FROM   mytable a
JOIN   mytable b ON a.name = b.name AND
                    a.date + INTERVAL '1' DAY = b.date AND
                    a.status <> b.status
chhkpiq4

chhkpiq42#

LAG() 以及 LEAD() 窗口功能:

select t.name, t.date, t.status
from (
  select *,
    coalesce(lag(status) over (partition by name order by date), status) prev_status,
    coalesce(lead(status) over (partition by name order by date), status) next_status
  from tablename  
) t
where t.status <> t.prev_status or t.status <> t.next_status
order by t.name, t.date

请看演示。
结果:

| name | date       | status    |
| ---- | ---------- | --------- |
| Dan  | 2020-06-02 | submitted |
| Dan  | 2020-06-03 | approved  |
| John | 2020-06-01 | submitted |
| John | 2020-06-02 | pending   |
| John | 2020-06-03 | approved  |
| Mary | 2020-06-03 | submitted |
| Mary | 2020-06-04 | pending   |

相关问题