首页 > 解决方案 > 如何对 Power Query 中的 N 列求和

问题描述

我的数据每个月都会更新,因此我正在尝试创建一个电源查询表,该表将显示我创建的旋转 (N) 列的总和,但我似乎无法弄清楚如何在电源查询中执行此操作。

我目前有这个代码:

在此处输入图像描述

在此处输入图像描述

标签: excelpowerquerym

解决方案


  • 转身后:
  • 创建要求和的列列表
  • 添加一个索引列以限制每一行
  • 添加一列,对仅该行的列求和
  • 删除索引列
let
    Source = Excel.CurrentWorkbook(){[Name="Table3"]}[Content],
    #"Changed Type" = Table.TransformColumnTypes(Source,{{"Month Yr", Date.Type}, {"Attribute", type text}, {"Value", Currency.Type}}),
    #"Added Custom" = Table.AddColumn(#"Changed Type", "MonthYear", each Date.ToText([Month Yr],"MMMM yyyy")),
    #"Removed Columns" = Table.RemoveColumns(#"Added Custom",{"Month Yr"}),
    #"Pivoted Column" = Table.Pivot(#"Removed Columns", List.Distinct(#"Removed Columns"[MonthYear]), "MonthYear", "Value", List.Sum),

//NEW code added after your Pivoted Column line

//Get List of columns to sum
//  Assumes this list all columns **except the first** in the Pivot table
//  There are other methods of generating this list if this assumption is incorrect
colToSum = List.RemoveFirstN(Table.ColumnNames(#"Pivoted Column"),1),

//Add Index Column
IDX = Table.AddIndexColumn(#"Pivoted Column","Index",0,1),

//Sum each row of "colToSum"
totals = Table.AddColumn(IDX, "Sum", each List.Sum(
        Record.ToList(
            Table.SelectColumns(IDX,colToSum){[Index]})
    ), Currency.Type),
    #"Removed Columns1" = Table.RemoveColumns(totals,{"Index"})


in
#"Removed Columns1"

在此处输入图像描述


推荐阅读