[英]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![]() |
SessionDate![]() |
---|---|
264 ![]() |
5/26/2021 ![]() |
264 ![]() |
5/27/2021 ![]() |
264 ![]() |
5/28/2021 ![]() |
264 ![]() |
5/19/2021 ![]() |
264 ![]() |
5/20/2021 ![]() |
264 ![]() |
5/21/2021 ![]() |
264 ![]() |
5/24/2021 ![]() |
264 ![]() |
5/25/2021 ![]() |
264 ![]() |
5/17/2021 ![]() |
264 ![]() |
5/18/2021 ![]() |
281 ![]() |
5/18/2021 ![]() |
281 ![]() |
5/25/2021 ![]() |
281 ![]() |
6/29/2021 ![]() |
281 ![]() |
6/1/2021 ![]() |
281 ![]() |
4/16/2020 ![]() |
281 ![]() |
4/23/2020 ![]() |
281 ![]() |
4/21/2020 ![]() |
281 ![]() |
4/28/2020 ![]() |
281 ![]() |
4/30/2020 ![]() |
281 ![]() |
5/5/2020 ![]() |
281 ![]() |
10/16/2019 ![]() |
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.