PowerQuery:如何连接分组值?

33
如果我有以下表格(如下图所示),那么我该如何编写一个分组查询来连接分组结果?

InputTable

对于这个例子,我希望按照LetterColumn分组并连接NumberColumn。因此,期望的结果是:

ResultsTable

3个回答

68
你可以使用图形用户界面来完成以下操作:
  1. 选择你的LetterColumn列,然后进行Transform / GroupBy操作: enter image description here

  2. 选择Add Column / Custom Column操作: enter image description here

  3. 点击新Custom列右上方的相对箭头以从新Custom列中提取值:

enter image description here enter image description here

  1. 删除AllData列。

9
太聪明了!你是怎么发现那个[AllData][NumberColumn]语法的?我用这个工具已经四年了,从来没有见过这个。 - Mike Honey
6
老实说,我不记得是从 @MikeHoney 哪里看到的,但我可能在 marcelbeug 的回复中看过。我从他那里学到了很多。要么就是我自己尝试了一下,然后它起作用了。;0) - Marc Pincince
7
天啊,这太有创意了。 - Gaspa79
3
  1. 这绝对是天才!
  2. Excel为什么没有一个简单的连接函数?
- Eugene Rosenfeld
2
@MarcPincince,我也成功地使用了你的方法一年多,但是在O365中看到了与@PE相同的问题。我认为PQ正在生成不正确的列表扩展。我看到这个:each Text.Combine(List.Transform(_, Text.From), ...) - 字面上是点点点,尽管已经选择了逗号。如果我将“...”更改为“,”,世界秩序就会恢复... - Jerry Norbury
显示剩余8条评论

18
如果你的表名为Source,且NumberColumn列是数字类型,则此公式可用:
= Table.Group(Source, {"LetterColumn"}, {{"Column", each Text.Combine(List.Transform(_[NumberColumn], (x) => Number.ToText(x)), ","), type text}}) Table.Group执行分组操作,生成一个由所有具有相同LetterColumn值的行组成的表格。 _[NumberColumn]给出了此新表中NumberColumn列中的值列表。 List.Transform将数字转换为文本值, Text.Combine将这些数字连接在一起,并用逗号隔开每个值。
如果你需要包含引号,可以使用以下公式:
= Table.Group(Source, {"LetterColumn"}, {{"Column", each """" & Text.Combine(List.Transform(_[NumberColumn], (x) => Number.ToText(x)), ",") & """", type text}}) """"代表 "字符, & 将两个文本值组合在一起。

1
GUI中如果有“合并文本”操作会很好。但是,与操作求和和选择列相比,需要进行一些小的调整:

enter image description here

我们可以直接得到这个结果,几乎是我们想要的:

enter image description here

= Table.Group(Source, 
    {"LetterColumn"}, 
    {{"NearlyGoodToGo", each List.Sum([NumberColumn]), type number}})

现在,需要直接更改代码的两个地方:

  • Text.Combine(List.Transform([NumberColumn], Text.From), ",")替换List.Sum[NumberColumn]
  • type text替换type number

我认为这是利用GUI获取基本模板,然后调整代码以避免使用GUI的All Rows操作和它产生的嵌套表格。

演示

let
    Source = Table.FromColumns({{"A","A","A","B","B","C","C","C","C"},{1..9}}, type table[LetterColumn = Text.Type, NumberColumn = Number.Type]),
    #"Grouped Rows" = Table.Group(Source, {"LetterColumn"}, {{"GoodToGo", each Text.Combine(List.Transform([NumberColumn], Text.From), ","), type text}})
in
    #"Grouped Rows" 

Results

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接