Calculated column with the sum of values from many columns in a row

陌路散爱 提交于 2019-12-11 04:46:33

问题


I need to sum all values in each row and display them in a calculated column. As I deal with lots of columns in lots of tables, adding something like

CalculatedColumn = 'public table_name'[column1] + 'public table_name'[column2] + ... + 'public table_name'[column528]

is really inefficient. Is there a shorter way of doing this?


回答1:


Yes, there is. You should "Unpivot other columns" and then "Group By" using the Query Editor.

  1. Suppose this dataset:

    item;col1;col2;col3;col4;col5
    apple;1;2;3;4;5
    orange;1;2;3;5;8
    banana;1;2;4;6;8
    
  2. Load it up, and open the query editor.

  3. Choose "Unpivot Other Columns":

    You should now see this:

  4. On the "Transform" tab in the ribbon, choose the leftmost "Group By" option. And fill out the dialog like so:

  5. You should now have the wanted end result:

You could also skip the Group By step and let your visualization handle that.

PS. Should you need a few non-summed columns too I recommend either creating a duplicate dataset with the same source and either linking it to the original table with a relationship, or merging it so you get a final table with all wanted columns.


Footnote, this is the Power Query that is generated for you:

let
    Source = Csv.Document(File.Contents("D:\Experiments\PowerBi\denormalized.csv"),[Delimiter=";", Columns=6, Encoding=1252, QuoteStyle=QuoteStyle.None]),
    #"Promoted Headers" = Table.PromoteHeaders(Source, [PromoteAllScalars=true]),
    #"Changed Type" = Table.TransformColumnTypes(#"Promoted Headers",{{"item", type text}, {"col1", Int64.Type}, {"col2", Int64.Type}, {"col3", Int64.Type}, {"col4", Int64.Type}, {"col5", Int64.Type}}),
    #"Unpivoted Other Columns" = Table.UnpivotOtherColumns(#"Changed Type", {"item"}, "Attribute", "Value"),
    #"Grouped Rows" = Table.Group(#"Unpivoted Other Columns", {"item"}, {{"SumCol", each List.Sum([Value]), type number}})
in
    #"Grouped Rows"


来源:https://stackoverflow.com/questions/42722567/calculated-column-with-the-sum-of-values-from-many-columns-in-a-row

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!