Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerQuery: How can I concatenate grouped values?

If I have the following table (shown in the image below), how can I write a grouped query that would concatenate the grouped results?

InputTable

For this example, I'd want to group by the LetterColumn and concatenate the NumberColumn

So the desired results would be:

ResultsTable

like image 841
Giffyguy Avatar asked May 18 '17 21:05

Giffyguy


People also ask

How do you concatenate rows by grouping data by column?

In the Advanced Combine Rows window, choose the column which you want to combine rows based on, and click Primary Key to set it as key column. 3. Select the column you need to combine, click Combine, and choose one delimiter you use to separate the combined contents.

Can you do a concatenate in Power Query?

Concatenate Text and Numeric Columns To do this, still within the Power Query Editor, click on the "Add Column" tab and then select "Custom Column" as done earlier. This time we will name the new column as "TextNumericCombine" as seen in the diagram below.


2 Answers

You can use the GUI to do it this way:

  1. Select your LetterColumn and then Transform / GroupBy: enter image description here

  2. Select Add Column / Custom Column: enter image description here

  3. Click opposing arrows at top right of new Custom column to Extract Values from new Custom column:

enter image description here enter image description here

  1. Remove AllData column.
like image 124
Marc Pincince Avatar answered Sep 18 '22 12:09

Marc Pincince


If your table is Source, and if NumberColumn has the number type, then this will work:

= Table.Group(Source, {"LetterColumn"}, {{"Column", each Text.Combine(List.Transform(_[NumberColumn], (x) => Number.ToText(x)), ","), type text}})

Table.Group does a group by operation, which creates a table made up of all of the rows with the same value in LetterColumn. _[NumberColumn] gives a list of the values in the NumberColumn column in this new table. The List.Transform part turns the numbers into text values, and Text.Combine joins those numbers together, with a comma separating each value.

If you need the surrounding quotes as well, you can do this:

= Table.Group(Source, {"LetterColumn"}, {{"Column", each """" & Text.Combine(List.Transform(_[NumberColumn], (x) => Number.ToText(x)), ",") & """", type text}})

"""" represents the " character, and & combines two text values.

like image 44
Alejandro Lopez-Lago - MSFT Avatar answered Sep 20 '22 12:09

Alejandro Lopez-Lago - MSFT