Forum Discussion
Mastering Table.Group in Power Query: Unlocking the fifth argument
Hello, Omid_Motamedise your 3rd usage of GroupKind.Local is so "unique" that I'd never recommend using it 😁 Have you ever tried it on lets say 5K rows of data? In Excel? Your code hits Source[Cost] list with List.Sum(List.Range(...)) so many times while you did not even bother with buffering it... Well, maybe I am wrong and PQ delegates this job to your source database (if it's your case) but I would prefer doing this with (pre-calculated) buffered list of running total cost.
let
Source = Table1,
cost = List.Buffer(Source[cost]),
rt_cost = List.Buffer(
List.Generate(
() => [i = 0, rt = cost{0}],
(x) => x[i] < List.Count(cost),
(x) => [i = x[i] + 1, rt = x[rt] + cost{i}],
(x) => x[rt]
)
),
res = Table.Group(
Source,
"Index",
{"Count", each List.Sum([cost])},
GroupKind.Local,
(s, c) => Number.From((rt_cost{c} - rt_cost{s}) >= 130)
)
in
res
Meanwhile, you may skip column reference in 5th argument (x[Index] or y[Index] in your code) and use just "x" and "y" if you use just single column to group by ("Index") and skip curley braces {} in 2nd argument of Table.Group.
Hi AlienSx ,
Thanks for pointing out Table.Buffer. I chose not to mention it to keep the solution simpler.
I also appreciate you sharing your solution—it's brilliant to use accumulated values instead of exact ones. However, when I applied your formula to the next set of data, the grouping resulted in sums like 142, 155, 170, 189, and so on. It stopped grouping when the total exceeded 130, whereas we need it to stop before reaching the max value.
| 9/07/2024 12:00:00 AM | 19 | 0 |
| 28/06/2024 12:00:00 AM | 55 | 1 |
| 26/07/2024 12:00:00 AM | 35 | 2 |
| 30/06/2024 12:00:00 AM | 33 | 3 |
| 4/06/2024 12:00:00 AM | 57 | 4 |
| 20/05/2024 12:00:00 AM | 30 | 5 |
| 10/07/2024 12:00:00 AM | 68 | 6 |
| 11/06/2024 12:00:00 AM | 55 | 7 |
| 11/06/2024 12:00:00 AM | 46 | 8 |
| 19/06/2024 12:00:00 AM | 69 | 9 |
| 7/06/2024 12:00:00 AM | 63 | 10 |
| 23/05/2024 12:00:00 AM | 62 | 11 |
| 2/07/2024 12:00:00 AM | 30 | 12 |
| 17/07/2024 12:00:00 AM | 34 | 13 |
| 13/08/2024 12:00:00 AM | 38 | 14 |
| 20/06/2024 12:00:00 AM | 63 | 15 |
| 31/05/2024 12:00:00 AM | 36 | 16 |
| 17/07/2024 12:00:00 AM | 45 | 17 |
| 10/06/2024 12:00:00 AM | 51 | 18 |
| 16/06/2024 12:00:00 AM | 69 | 19 |
| 19/07/2024 12:00:00 AM | 27 | 20 |
| 16/06/2024 12:00:00 AM | 14 | 21 |