I have a history table for the user, and I'm trying to find date ranges in which the user has a specific username. The table is an audit table that is populated with a trigger, so it has entries every time there is a change for the user, and not just for the username. I can do this to get a date range for each row:
CREATE TABLE
Output:
LoginID Username StartDate EndDate 1 t 2016-01-01 00:00:00.000 2016-01-02 00:00:00.000 1 t 2016-01-02 00:00:00.000 2016-01-04 00:00:00.000 1 t 2016-01-04 00:00:00.000 2016-01-05 00:00:00.000 1 test 2016-01-05 00:00:00.000 2016-01-15 00:00:00.000 1 test 2016-01-15 00:00:00.000 2016-02-01 00:00:00.000 1 t 2016-02-01 00:00:00.000 NULL
However, I would really like to do this in order to reduce each username duration so that one line per date range contains the username. Basically, I am looking for this conclusion:
LoginID Username StartDate EndDate 1 t 2016-01-01 00:00:00.000 2016-01-05 00:00:00.000 1 test 2016-01-05 00:00:00.000 2016-02-01 00:00:00.000 1 t 2016-02-01 00:00:00.000 NULL
How can I collapse these lines correctly?
source share