LightClub.
Menu
Explore the blog

Keep the Latest Row in Power Query for Each Customer

Sorting and removing duplicates can retain the wrong record. Define which record should win, then select it within each customer group.

lightclub_owner6 min read
Illustration of the latest row in Power Query for two synthetic customers: C001 revision 103 and C002 revision 202.

A customer export can contain several versions of the same record. To keep the latest row in Power Query for each customer, define which timestamp wins and how tied revisions should be resolved.

Example verification: These are synthetic examples with expected results. The steps have been reviewed against documentation but not yet tested in Power Query.

The solution is to group by customer ID, order each group by its update timestamp, and take its first row. If two rows share a timestamp, use a second field that defines which version wins.

Why sorting and removing duplicates can fail

Power Query can optimize transformations or send some work back to the data source. Microsoft explains that duplicate removal does not guarantee which matching record survives [1]. A table that looks correctly sorted in the editor is therefore not sufficient evidence that the final result will always retain the intended row.

Instead, make the selection part of the grouping operation itself. This also makes your tie-breaking rule visible to anyone maintaining the query.

Try this example

The following synthetic records represent five updates to two customer accounts. All timestamps use the same time zone. The larger RecordID is defined as the later revision when timestamps tie.

CustomerIDUpdatedAtRecordIDStatus
C0012026-04-03 09:00101Pending
C0022026-04-02 08:00201New
C0012026-04-04 10:30102Active
C0012026-04-04 10:30103Verified
C0022026-04-05 12:00202Active

C001 should retain record 103, not 102. C002 should retain record 202. This is a more useful test than a dataset where all timestamps differ.

Step 1: Check the column types

Open your data in the Power Query Editor. Make sure CustomerID is text, UpdatedAt is a date/time value, and RecordID is a whole number. Sorting text timestamps is not a dependable substitute for sorting correctly parsed dates, especially with regional date formats.

Check for missing customer IDs, missing timestamps, and duplicate version identifiers before choosing a winner. Decide what to do with these exceptions instead of silently dropping them.

Step 2: Select the Latest Row in Power Query

To reproduce the example in Power Query Desktop, create a blank query and open Advanced Editor. Replace the sample query with the following M code.

let
    Source = #table(
        type table [CustomerID = text, UpdatedAt = datetime,
                    RecordID = number, Status = text],
        {
            {"C001", #datetime(2026, 4, 3, 9, 0, 0), 101, "Pending"},
            {"C002", #datetime(2026, 4, 2, 8, 0, 0), 201, "New"},
            {"C001", #datetime(2026, 4, 4, 10, 30, 0), 102, "Active"},
            {"C001", #datetime(2026, 4, 4, 10, 30, 0), 103, "Verified"},
            {"C002", #datetime(2026, 4, 5, 12, 0, 0), 202, "Active"}
        }
    ),
    Grouped = Table.Group(
        Source,
        {"CustomerID"},
        {{"Latest", each Table.First(Table.Sort(_, {
            {"UpdatedAt", Order.Descending},
            {"RecordID", Order.Descending}
        })), type record}}
    ),
    Expanded = Table.ExpandRecordColumn(
        Grouped, "Latest",
        {"UpdatedAt", "RecordID", "Status"},
        {"UpdatedAt", "RecordID", "Status"}
    ),
    Result = Table.Sort(Expanded, {{"CustomerID", Order.Ascending}})
in
    Result

The Grouped step operates on the rows for one customer at a time [2]. The two descending sort keys determine the winning record [3]. Table.First selects that row [4]. The Expanded step restores its fields as normal columns. The final sort is only for presentation.

For your own data, replace the Source step with your existing, correctly typed input query. Update the key and expanded column names to match your data.

Step 3: Verify the output before using it

The expected result for the sample is:

CustomerIDUpdatedAtRecordIDStatus
C0012026-04-04 10:30103Verified
C0022026-04-05 12:00202Active

Check that the result has exactly two rows and that each row matches an original record. Reverse the order of the input rows and refresh. The same records should win because the choice is based on values, not the original position.

If the timestamp and RecordID can both tie, add a genuinely unique version key or define a separate conflict-resolution process. If IDs are not chronological, a larger ID is not a valid proxy for recency. Similarly, normalize timestamps if your source mixes time zones.

When this method is not appropriate

If you need to keep every row from the latest timestamp, taking one row is the wrong business rule. Filter each group to its maximum timestamp instead, preserving all tied records. For very large database-backed datasets, also consider implementing the same explicit ranking rule in the source database and checking performance.

Compare actual instants when time zones differ

If updates arrive from more than one time zone, a later wall-clock time may be the earlier event. For example, 10:30 with a +03:00 offset is 07:30 UTC, while 08:15 with a +00:00 offset is 08:15 UTC. The second update is later. Preserve trustworthy offsets and convert timezone-aware values to a common basis before ranking them. Microsoft documents DateTimeZone.ToUtc for this conversion. [5]

Keep the original timestamp and the normalized value in separate columns during review. If a field arrives without an offset, obtain its timezone convention from the source. Attaching UTC to a local clock reading does not convert it to the correct instant. Confirm whether the business means most recently updated, most recently received, or latest effective date. Those fields can disagree when late data arrives.

10:30 +03:00  =  07:30 UTC. 08:15 +00:00  =  08:15 UTC. Later instant: 08:15 UTC.
Normalize offsets before deciding which event is latest.

Validate ties, missing keys and refresh behavior

To check the latest row in Power Query, extend the synthetic sample with a record that has the same customer, timestamp and revision as the winner but a different status. The existing two sort keys no longer determine a unique row. Mark it as a conflict in your QA process. Add another sort key only if the business has a defensible rule for what it means to win. A random identifier can make a choice repeatable without making it correct.

Check missing customer IDs before grouping. Several unlabelled rows might otherwise be treated as one group even though they represent different customers. Keep missing or ambiguous rows separate for review. Decide whether an absent timestamp makes an update invalid or requires another backfill field. Compare the count of valid distinct customer IDs in the input with the output count after excluding exceptions.

Refresh once with the input order reversed, then add a newer revision for one customer and refresh again. Only that customer’s selected row should change. Compare complete output records with their source rows, including Status. A maximum timestamp and a separately computed maximum revision can describe different rows. Selecting the complete winner preserves the pairing. [2, 3, 4]

1  Match customer ID. 2  Sort timestamp and revision. 3  Review equal winning keys.
Check the keys in order and flag exact ties for review.

Sources

[1] Microsoft Learn, Table.Distinct: https://learn.microsoft.com/powerquery-m/table-distinct

[2] Microsoft Learn, Table.Group: https://learn.microsoft.com/en-us/powerquery-m/table-group

[3] Microsoft Learn, Table.Sort: https://learn.microsoft.com/en-us/powerquery-m/table-sort

[4] Microsoft Learn, Table.First: https://learn.microsoft.com/en-us/powerquery-m/table-first

[5] Microsoft Learn, DateTimeZone.ToUtc: https://learn.microsoft.com/en-us/powerquery-m/datetimezone-toutc

Keep your curiosity switched on.

Explore more practical guides and ideas from LightClub.

About LightClub

Leave a Reply

Your email address will not be published. Required fields are marked *

Keep reading.

All articles