简体   繁体   English

Sql function 查找每组两个连续行之间的日期差异

[英]Sql function find date difference between two consecutive rows per group

I am working on clinical data to find total sessions for patients by finding date difference.我正在研究临床数据,通过查找日期差异来查找患者的总疗程。 I can achieve this using Python but power bi does not support that script.我可以使用 Python 来实现这一点,但 power bi 不支持该脚本。 So I needed help to do this in SQL.所以我需要帮助在 SQL 中执行此操作。 I am basic level user of SQL so have no idea how to start for this.我是 SQL 的基本用户,所以不知道如何开始。

Below is raw data下面是原始数据

PatientID患者 ID SessionDate会议日期
264 264 5/26/2021 2021 年 5 月 26 日
264 264 5/27/2021 2021 年 5 月 27 日
264 264 5/28/2021 2021 年 5 月 28 日
264 264 5/19/2021 2021 年 5 月 19 日
264 264 5/20/2021 2021 年 5 月 20 日
264 264 5/21/2021 2021 年 5 月 21 日
264 264 5/24/2021 2021 年 5 月 24 日
264 264 5/25/2021 2021 年 5 月 25 日
264 264 5/17/2021 2021 年 5 月 17 日
264 264 5/18/2021 2021 年 5 月 18 日
281 281 5/18/2021 2021 年 5 月 18 日
281 281 5/25/2021 2021 年 5 月 25 日
281 281 6/29/2021 2021 年 6 月 29 日
281 281 6/1/2021 2021 年 6 月 1 日
281 281 4/16/2020 2020 年 4 月 16 日
281 281 4/23/2020 2020 年 4 月 23 日
281 281 4/21/2020 2020 年 4 月 21 日
281 281 4/28/2020 2020 年 4 月 28 日
281 281 4/30/2020 2020 年 4 月 30 日
281 281 5/5/2020 2020 年 5 月 5 日
281 281 10/16/2019 2019 年 10 月 16 日

Expected output is as below预期的 output 如下

预期数据

Based on @Akina hint I was able to get the required output from following query Note:- My sessionDate column was in Date and timestamp format.根据@Akina 提示,我能够从以下查询中获得所需的 output 注意:-我的 sessionDate列采用日期和时间戳格式。

select
        t.PatientID,

        CAST(t.SessionTimestamp as Date) as SessionDate,

        LAG(t.SessionTimestamp) over(partition by t.PatientRecordId order by t.PatientID,t.SessionTimestamp) as Next_Date  


from mytable t

order by
t.PatientID,
t.SessionTimestamp

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM