Link to home
Start Free TrialLog in
Avatar of ExtremeFitness
ExtremeFitness

asked on

How do I compare two rows within the same table?

I have a table with memberid, session # and session date
How can I identify the row that is at least X days after the previous?

ASKER CERTIFIED SOLUTION
Avatar of Yveau
Yveau
Flag of Netherlands image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of ExtremeFitness
ExtremeFitness

ASKER

Figured it out.. Much faster than a join. :)


SELECT CustomerId,
      CAST(Session_date AS CHAR(11)) AS 'SessDate',
      CAST(NextDate AS CHAR(11)) AS NextDate,
      DATEDIFF(DAY, Session_date, NextDate)
FROM (
      SELECT DISTINCT PT.CustomerId, PT.Session_Date,
            (SELECT MIN(Session_Date)
                  FROM Personal_Training1 AS PTMin
                  WHERE PTMin.Session_Date > PT.Session_Date AND PTMIN.CustomerId = PT.CustomerId) AS 'NextDate'
      FROM Personal_Training1 AS PT
      WHERE CustomerId = 31790
) AS PTCheck
ORDER BY Session_date

Thanks for the help.  :)
Glad I could be of any help ... but your solution is a self join as well :-)