简体   繁体   中英

Compare same column in consecutive rows in same table with multiple ID's

I have a user request for a report and I'm too new to SQL programming to know how to approach it.

My user wants to know for each Staff ID what is the min, avg and max number of days between visits. What I don't know how to figure out is the number of days between Visit 1 and Visit 2; Visit 2 and Visit 3, etc., for each Person ID. Some Person ID's only have one visit, others (most) have multiple visits (up to 26). Here is a snapshot of some data (the full dataset is over 14k records):

PersonID    VisitNo    StaffID    VisitDate  
161          1         42344      06/19/2018
163          1         32987      05/14/2018
163          2         32987      09/17/2018
193          1         42344      04/09/2018
193          2         42344      07/18/2018
193          1         33865      07/18/2018  
207          1         32987      10/10/2018
207          2         32987      11/05/2018 
329          1         42344      04/15/2018
329          2         42344      05/23/2018
329          3         42344      06/10/2018
329          4         42344      07/18/2018
329          1         33865      06/30/2018
329          2         33865      09/14/2018

My research found a lot of references to comparing rows in the same table and I figured out how to compare one visit to the next for a single PersonID using a self join and datadiff, but how do I get from one PersonID to the next, or skip those PersonID's with only 1 visit? Or a PersonID who has visits with multiple StaffId's?

Any ideas/suggestions are greatly appreciated as I have two requests that will benefit.

You can use analytic function LEAD (myvar,1) OVER ()

example from https://www.techonthenet.com/sql_server/functions/lead.php

SELECT dept_id, last_name, salary,
LEAD (salary,1) OVER (ORDER BY salary) AS next_highest_salary
FROM employees;

For the average number of days, you can just use aggregation:

select personid,
       (datediff(day, min(visitdate), max(visitdate)) * 1.0 / nullif(count(*) - 1, 0)
from t
group by personid;

I used SQL Server syntax, but the same idea holds in any database. The average is the maximum minus the minimum divided by one less than the number of visits.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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