Finding date difference in same column based on variables in a second column--SQL

Viewed 23

I would like to find the days between consult dates (if a patient has more than 1 date), and then eventually eliminate the cases where the consults come within 7 days of each other for the same patient. Getting the difference in days is my obstacle. Thinking I need to use a partition and date difference function but not sure how to do it in an efficient manner. Thank you in advance for your time and insights!

Current data looks something like below:

Patient          Consult Date
A             2022-07-14 08:41:59
B             2022-07-01 11:23:59
B             2022-07-01 12:34:15
B             2022-01-04 09:25:14
B             2021-10-30 10:45:56
C             2022-07-24 14:55:43
C             2022-03-14 10:11:46
C             2022-03-14 09:35:22

I would like the data to look like:

Patient           Consult Date            Difference(Days)
A             2022-07-14 08:41:59          N/A
B             2022-07-01 11:23:59          0
B             2022-07-01 12:34:15          183
B             2022-01-04 09:25:14          64
B             2021-10-30 10:45:56          N/A
C             2022-07-24 14:55:43          130
C             2022-03-14 10:11:46          0
C             2022-03-14 09:35:22          N/A
1 Answers

if you want calculate date difference between tow date time parameter first convert to varchar and then get difference like this.

declare @startDate datetime , @endDate datetime , @dateDiffrence varchar (max)

set @startDate = CONVERT(varchar(max),B1) set @endDate = CONVERT(varchar(max),B2)

set @dateDiffrence = DATEDIFF(DAY, @endDate, @startDate)

so @dateDiffrence is your difference between two date time.

I hope it is useful for you.

Related