Comparing database records
This page compares each record in a table with the record before it. The technique is to add two index columns, one starting at 1 and one at 0, and then merge the table with itself on those columns, so that every row is joined to the row above it.
The example is a list of service desk tickets for several customers. The question is whether a customer opened a new ticket within 7 days of closing their previous one.

1. Query the table and sort it
Section titled “1. Query the table and sort it”- Click inside the table, and on Excel’s Data tab click From Table/Range. The data opens in the Power Query Editor. Check that Open Date and Close Date have the Date type.

- Sort the table by Customer, and then by Open Date, both ascending. Each customer’s tickets are then together, in the order they were opened.

2. Add two index columns
Section titled “2. Add two index columns”- On the Add Column tab, open the Index Column list and choose From 1.
- Add a second index column, choosing From 0 this time.
On every row, the second index is one less than the first, so it holds the first index of the row above. This is what links a record to the previous one.

- Rename the second index column Previous.
3. Merge the table with itself
Section titled “3. Merge the table with itself”- On the Home tab, click Merge Queries. Choose the current query again as the second table, select Previous in the upper table and Index in the lower table, and click OK.

The merge adds a column of tables, named Renamed Columns after the step it merged with. Each table holds the row above.

- Remove the Index and Previous columns, which are no longer needed.
- Click the expand icon in the Renamed Columns header, tick only Customer and Close Date, and click OK.

- Rename the expanded Close Date column Previous Close Date. The expanded customer column is called Customer.1.
Each row now shows the customer and close date of the ticket above it. The first row has nulls, because no ticket comes before it.

4. Flag the repeat tickets
Section titled “4. Flag the repeat tickets”The test is whether the previous ticket belongs to the same customer and closed no more than 7 days before this ticket opened. Comparing the customers matters, because at the boundary between two customers the row above belongs to someone else.
- On the Add Column tab, click Custom Column, and enter this formula:
= if [Customer] = [Customer.1] and Duration.Days([Open Date] - [Previous Close Date]) <= 7 then "Repeat Ticket" else nullDuration.Days turns the difference between the two dates into a whole number of days.

- Click OK. The new column shows Repeat Ticket where the rule is met, and null elsewhere.

- Remove the Customer.1 and Previous Close Date columns, and click Close & Load to load the result to a table.
The final table marks the two tickets that Cust 1 opened within 7 days of closing an earlier one.
