Forum Discussion

Anonymous's avatar
Anonymous
Not applicable
6 years ago
Solved

Identifying the 2 most recent days in Power Query

Hi, I would like to create a dynamic filter that identifies the 2 most recent days in a new column   My code for that step thus far is: = Table.AddColumn(#"Added Conditional Column", "Custom.1", ...
  • Jimmy801's avatar
    6 years ago

    Hello Anonymous 

     

    check out this solution. It involves of creating a list of the 2 latest dates in a date-column. This list is then used to filter the whole table

    let
    	Source = #table
    	(
    		{"Date","Column1"},
    		{
    			{"43466","test1"},	{"43678","test2"},	{"43554","test3"},	{"43819","test4"},	{"43831","test5"},	{"43833","test6"},	{"43838","test7"},	{"43851","test8"},	
    			{"43851","test9"},	{"43848","test10"}
    		}
    	),
        ToDate = Table.TransformColumns
        (
            Source,
            {
                {
                    "Date",
                    each Date.From(Number.From(_)),
                    type date
                }
            }
        ),
        GetListToFilter = List.FirstN
        (
             List.Sort
            (
                List.Distinct
                (
                    ToDate[Date]
                ),
                Order.Descending
                
            ),
            2
        ),
        SelectRows = Table.SelectRows
        (
            ToDate,
            (row)=>
            List.Contains
            (
                GetListToFilter,
                row[Date]
            )
        )
    in
    	SelectRows

     

    Copy paste this code to the advanced editor in a new blank query to see how the solution works. If this solution fits your need, copy and past a part of it and implement it in your query, or I could create a custom function what makes it easier to apply if you are not used that much to power query.

    If this post helps or solves your problem, please mark it as solution (to help other users find useful content and to acknowledge the work of users that helped you)
    Kudoes are nice too

    Have fun

    Jimmy