Search code examples
excelgroupingpowerquerysubtotal

How to add totals row to excel power query?


I have produced a table like the one below by using 'group' function in excel power query

score 1 score 2 score 3
A   6   25  50
B   8   30  20
C   15  15  30
D   20  0   10

I want to add a totals row (equivalent to "show totals for column" in a normal pivot table), so result would be like this

score 1 score 2 score 3
A   6   25  50
B   8   30  20
C   15  15  30
D   20  0   10
Total 49    70      110

Anyone knows if there is a simple way to do this? Thank you, RY


Solution

  • Another way:

    let
        Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
        group = Table.Group(Source, {}, {{"letter", each "Total"},
                                         {"score 1", each List.Sum([score 1])},
                                         {"score 2", each List.Sum([score 2])}, 
                                         {"score 3", each List.Sum([score 3])}}),
        append = Table.Combine({Source, group})
    in
        append
    

    Or:

    let
        Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
        cols = Table.ColumnNames(Source),
        group = Table.Group(Source, {}, List.Zip({cols, {each "Total"}&
                                        List.Transform(List.Skip(cols), 
                                        (x)=>each List.Sum(Table.Column(_,x)))})),
        append = Table.Combine({Source, group})
    in
        append
    

    Or:

    let
        Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
        group = Table.Group(Source, {}, List.TransformMany(Table.ColumnNames(Source),
                                        (x)=>{each if x = "letter" then "Total" 
                                        else List.Sum(Table.Column(_,x))}, (x,y)=>{x,y})),
        append = Table.Combine({Source, group})
    in
        append