简体   繁体   中英

Power BI M Language List.Select How to filter by Date

When I use this: List.Select({[Date1], [Date2], [Date3]}, each _ < [Date4]) it returns error. But when I use this code: List.Select({"2020-01-01", "2020-02-01", "2020-03-01"}, each _ < "2020-04-01") it returns a list of values.

First, I assume this is in the context of a function like Table.AddColumn - if that is so, then the cause of your error is: you are referencing the inner function's list item parameter instead of the outer function's table record parameter with the "[Date4]" reference.

The fix is easier to see once you expose the full code under the syntax sugar involved: simply use a different identifier for your inner parameter.

    List.Select(
            {[Date1],[Date2],[Date3]},
            (ListItem)=> ListItem < [Date4]
    )

How does the above work? Look at the full M code of the original for an idea, again assuming we are using a function like Table.AddColumn:

= Table.AddColumn(
    Table1, 
    "New Column Name", 
    each List.Select(
        {[Date1],[Date2],[Date3]},
         each _ < [Date4]
    )
)

We can see there are actually two each's at play. Three points to help us understand the problem:

  1. "each" is syntax sugar for "(_)=>" which defines a function where the passed parameter is referenced with "_"
  2. the value passed to the outer each is the current row of the table as a record where each column/value in the row is a field in said record; the square brackets are used to access fields in a record
  3. Reference to a field with no record assumes "_" is the record, eg "[Date1]" without specifying the record is just syntax sugar for "_[Date1]"

With the above points, we can rewrite the code as follows

    = Table.AddColumn(
        Table1, 
        "New Column Name", 
        (_)=> List.Select(
            {_[Date1],_[Date2],_[Date3]},
            (_)=> _ < _[Date4]
        )
    )

Now you can see there is an outer "_" referencing each row of the table as a record which allows us to access the fields with for example "_[Date1]". The inner "_", on the other hand, is accessing each value of the input list. So, in the context of the innermost function, "_ < _[Date4]", the "_" refers to only the inner "_" - ie you are trying to access a record field from a date value, causing an error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM