Skip to main content
cancel
Showing results for 
Search instead for 
Did you mean: 

Enhance your career with this limited time 50% discount on Fabric and Power BI exams. Ends August 31st. Request your voucher.

Reply
fugazzetta
Frequent Visitor

How to flag the first 2 rows that meet a condition using M CODE Power query?

As the title say, if i have a table with 3 rows, and i want to add a flag to the first two rows that meet a condition, how can i do that in M code? 

Invoice IDTypeWeightDestinationSale ID
A32Invoice10F1
A14Credit note-10F1
A33Invoice10D1


In this example I have a list of invoices with different details and values (this is just an mock up example, can't post the real table). Sometimes due to a mistake while completing an invoice they have to cancell the invoice creating a credit note. See example: first row is the created invoice with destination F, but the correct destination was D, so they first create a credit note that cancells the invoice, and then they create an invoice with the correct destination. Notice how the credit note has a negative numeric value to indicate it's cancelling the first one. 

What I want to do is create a custom column using M code in power query that flags the first two rows so that i can then know which inoices have been cancelled, and then flags the third row which is the one that's correct. 

Invoice IDTypeWeightDestinationSale IDFlag
A32Invoice10F1N
A14Credit note-10F1N
A33Invoice10D1Y

 


Also I would like to add a Y flag if there's only one apparence of the row, meaning there was no cancellation asociated with that sale ID. 


1 REPLY 1
ddpl
Solution Sage
Solution Sage

@fugazzetta 

In Power Query, First you group by your dataset as shown below...

bin21.png

 

then, expand the rest column...

bin22.png

 

Add a custom column...

Flag = if [Invoice_ID_New] = [Invoice ID] then "Y" else "N"

 

After that remove Invoice_ID_N column.

 

You will get your required column Flag.

Helpful resources

Announcements
July 2025 community update carousel

Fabric Community Update - July 2025

Find out what's new and trending in the Fabric community.

July PBI25 Carousel

Power BI Monthly Update - July 2025

Check out the July 2025 Power BI update to learn about new features.