2

我在 PowerQueryCityPeople.

城市

Id, Name
 1, Brisbane
 2, Sydney
 3, Melbourne

人们

Id, Name,  CityId
 1, Jay,   1
 2, Sam,   2
 3, Paul,  1
 4, Sarah, 3

我想在 City 添加一列,显示属于该城市的人数。到目前为止,我有:

Table.AddColumn(City, "People.Count", each
    Table.RowCount(
        Table.SelectRows(
            People, 
            each [CityId] = [Id]
        )
    )
)

这将在新列中返回全零。如果我替换[Id]1then 我得到2.

它似乎[]引用了当前行但在同一个表上的值。有没有办法我可以把它写成

Table.AddColumn(City, "People.Count", each 
    Table.RowCount(
        Table.SelectRows(
            People, 
            each People[CityId] = City[Id]
        )
    )
)

在 Excel 中,这将是基本的

=COUNTIF(People[CityId],[@Id])

然后在PEOPLE中拉下新列(根据附加的 .xlsx)

看起来很简单,但绝对卡住了!哎呀。

4

3 回答 3

3

Ah, now I see what you're after. There's a nifty trick to do it with a simple column:

= Table.AddColumn(City, "People.Count", each let Id=[Id] in Table.RowCount(Table.SelectRows(People, each [CityId] = Id)))

You need to define the column name as a variable in order to "leave" the current "context" you're in (People's table).

于 2016-02-01T16:47:52.523 回答
3

I would build a Query that starts from PEOPLE, and then Groups By City and calculates a Count.

Then I would Merge the CITY query with that new Query and expand the Count column.

No code or formulas are required - it's actually simpler than Excel formulas.

于 2016-02-01T06:22:09.837 回答
2

还有其他关于如何以不同方式编写的答案,但这里最通用的解决方案可能是删除嵌套each语法。

查看您的查询可能会有所帮助

Table.AddColumn(
    City,
    "People.Count", each 
      Table.RowCount(Table.SelectRows(
        People, 
        each [CityId] = [Id])))

是这个重写版本的语法糖。在_[CityId] = _[Id]表达式中,_变量被绑定到最里面的参数,而最外面_的没有被使用:

Table.AddColumn(
    City,
    "People.Count", (_) =>
      Table.RowCount(Table.SelectRows(
        People, 
        (_) => _[CityId] = _[Id])))

如果您曾经有嵌套each表达式,我会将外部更改为each具有真实变量名的函数,如下所示:

Table.AddColumn(
    City,
    "People.Count", (CityRow)  =>
      Table.RowCount(Table.SelectRows(
        People, 
        each [CityId] = CityRow[Id])))
于 2016-02-01T23:15:14.610 回答