cancel
Showing results for 
Search instead for 
Did you mean: 
Reply
julioagh
Frequent Visitor

Remove the Last N rows of a given set of data

Hi I have this sample data, I want to remove the last 2 rows of a given set of data. For example in this case I want to remove the selected ones in red because its only allowed to have 2 records per combination

#"sample"

ID1ID2
11
12
13
14
21
22
31
32
33

 I get to these code but its incomplete. I dont know if need another approach or if is possible to iterate each row of the #"sample for distinct ID1s

 

 

#"ID1 Table" = Table.SelectColumns(#"sample",{"ID1"}),
#"Distinct ID1 Table" = Table.Distinct(#"ID1 Table"),

.... //Missing code

#"Last records" = Table.SelectRows(table,each [ID1] <> ID1Filter), //ID1Filter is a distinct ID1 from table
#"ID2 from ID1"= Table.SelectRows(table,each [ID1] = ID1Filter),
#"quantity Of ID2" = Table.RowCount(#"ID2fromID1"),
#"Last ID2 fromI D1"= Table.RemoveLastN(#"ID2 from ID1",if #"quantity Of ID2"> 2 then #"quantity Of ID2"- 2 else 0),
#"Removed"= Table.Combine({#"Last records",#"LastID2fromID1"})

 

 

1 ACCEPTED SOLUTION
CNENFRNL
Community Champion
Community Champion

let
    Source = Table.FromRows(Json.Document(Binary.Decompress(Binary.FromText("i45WMlTSAeJYHQjLCM4yhrNMwCwjuDojuDpjuJgxihhQbywA", BinaryEncoding.Base64), Compression.Deflate)), let _t = ((type nullable text) meta [Serialized.Text = true]) in type table [ID1 = _t, ID2 = _t]),
    Grouped = Table.Group(Source, "ID1", {"a", each if Table.RowCount(_) > 2 then Table.FirstN(_, 2) else _}),
    #"Expanded a" = Table.ExpandTableColumn(Grouped, "a", {"ID2"}, {"ID2"})
in
    #"Expanded a"

Screenshot 2021-06-17 021555.png

View solution in original post

2 REPLIES 2
julioagh
Frequent Visitor

Love the simplicity of your solution!. Thank you so much!

CNENFRNL
Community Champion
Community Champion

let
    Source = Table.FromRows(Json.Document(Binary.Decompress(Binary.FromText("i45WMlTSAeJYHQjLCM4yhrNMwCwjuDojuDpjuJgxihhQbywA", BinaryEncoding.Base64), Compression.Deflate)), let _t = ((type nullable text) meta [Serialized.Text = true]) in type table [ID1 = _t, ID2 = _t]),
    Grouped = Table.Group(Source, "ID1", {"a", each if Table.RowCount(_) > 2 then Table.FirstN(_, 2) else _}),
    #"Expanded a" = Table.ExpandTableColumn(Grouped, "a", {"ID2"}, {"ID2"})
in
    #"Expanded a"

Screenshot 2021-06-17 021555.png

View solution in original post

Helpful resources

Announcements
UG GA Amplification 768x460.png

Launching new user group features

Learn how to create your own user groups today!

Power BI October Update 2021.jpg

Power BI Release

Click here to read more about the October 2021 Release!

Community Connections 768x460.jpg

Community & How To Videos

Check out the new Power Platform Community Connections gallery!

Teds Dev Camp Oct. 2021 768x460.jpg

Power BI Dev Camp - October 28th, 2021

Mark your calendars and join us for our next Power BI Dev Camp!

Top Solution Authors
Top Kudoed Authors