Sum column based on criteria while grouping in Power Query.
A little trick I created once while working with some data.
The data:
Group By | Criteria | Value 1 | Value 2 |
---|---|---|---|
Group 1 | All | 35 | 20 |
Group 1 | All | 30 | 40 |
Group 1 | All | 35 | 40 |
Group 1 | Partial | 25 | 20 |
Group 1 | Partial | 35 | 50 |
Group 1 | All | 50 | 45 |
Group 2 | Partial | 30 | 45 |
Group 2 | All | 40 | 30 |
Group 2 | Partial | 20 | 30 |
Group 2 | Partial | 15 | 30 |
Group 2 | All | 45 | 20 |
The required result was to get the sum of “VALUE 1” regardless and the sum of “VALUE 2” only if “GROUP BY” is equal to “Partial”.
This is my formula:
Table.Group (
#"Data Table",
{
"Group By"
},
{
{
"All",
each List.Sum ( [Value 1] ),
Int64.Type
},
{
"Partial",
each List.Sum (
Table.Column (
Table.SelectRows (
_,
each [Criteria] = "Partial"
),
"Value 2"
)
),
Int64.Type
}
}
)
Resulting in this table:
Group By | All | Partial |
---|---|---|
Group 1 | 210 | 70 |
Group 2 | 150 | 105 |
Explanation:
I grouped the table using “Table.Group” with the “Group By” column as the group by column and I am creating 2 result columns “All” and “Partial” (the sum of “Value 1” only where “Criteria” equals “Partial”). The “All” result is the simple “List.Sum” on the “Value 1” column and for the “Partial” result I Filtered the table based on the “Criteria’ column only where it matched “Partial” and the I used “List.Sum” on “Value 2” from the sub-filtered table.
I hope you find my code useful!