PowerQuery COUNTIF Previous Dates

冷暖自知 提交于 2020-01-25 11:27:25

问题


I'm a little rusty on PowerQuery.
I need to count "previous" entries in the same table.

For example, let's say we have a table of car sales.
For the purposes of PowerQuery, this table will be named tblCarSales

I need to add two aggregate columns.

The first aggregate column is the count of previous sales.
The Excel formula would be =COUNTIF([Sale Date],"<"&[@[Sale Date]])

The second aggregate column is the count of previous sales by make.
The Excel formula would be =COUNTIFS([Sale Date],"<"&[@[Sale Date]],[Make],[@Make])

How can this behavior be accomplished in PowerQuery, instead of using Excel formulas?
For example, I'm starting with the source statement:

let
    Source = Excel.CurrentWorkbook(){[Name="tblCarSales"]}[Content]
in
    Source

... where the source table only provides the Make, Model, and Sale Date columns.


回答1:


You can do this sort of thing using List and Table functions. I'll show both.

let
    Source = Excel.CurrentWorkbook(){[Name="tblCarSales"]}[Content],
    #"Added Custom" = Table.AddColumn(Source, "Previous Sale Count",
                         (C) => List.Count(List.Select(Source[Sale Date],
                                each _ < C[Sale Date]))),
    #"Added Custom1" = Table.AddColumn(#"Added Custom", "Previous Sale Count By Make",
                         (C) => Table.RowCount(Table.SelectRows(Source,
                                (S) => S[Sale Date] < C[Sale Date] and S[Make] = C[Make])))
in
    #"Added Custom1"

We have to use the functions so that Power Query knows what context we're looking at the columns in. For further reading, check out this Power Query M Primer.



来源:https://stackoverflow.com/questions/51304608/powerquery-countif-previous-dates

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!