在Power BI中的不同列上从同一列中减去两行

Subtracting two rows from same column with condition on different column in Power BI

我正在 Power Bi 中创建一个 table,其中我有工作级别,对于每个工作级别,我有两行,第一行用于“现有员工”,第二行用于“新员工”。现有员工和新员工有补偿比率。我想创建一个新列,提供每个工作级别的新员工薪酬比率和现有员工薪酬比率之间的差异。如果结果为负,则显示空白,否则显示结果。

如下所示:

Job Level   Employee Group  Comp Ratio  Difference
3            Existing             108%         -108 ( don't show this)
3            New Hire             0%
4            Existing             107%          3
4            New Hire             110%
5            Existing             104%         -1 (Don't show this)
5            New Hire             103%

谢谢, CSTech

截图如下:

您可以在 Power Query M 代码中执行此操作

  • 进入 Power Query 编辑器Home => Transform Data
  • 进入高级编辑器Home => Query => Advanced Editor
  • 在编辑器中删除,最后几行in ...
  • 开头
  • 在您的代码的新结尾后粘贴下面的代码
  • 在新粘贴的代码的第一行,将 #"Previous Step" 更改为代码中实际上一步的名称。

算法

  • 按职位级别分组
  • 为每个分组子添加一列table
    • 如果 Employee GroupNew Hire 那么写一个 null
    • 如果 Comp Ratio 列中的第二个条目大于第一个条目,则减去并写入差值,否则写入 'null'
//Add this to your code
    #"Grouped Rows" = Table.Group(#"Previous Step", {"Job Level"}, {
        {"Difference", (t)=> Table.AddColumn(t,"Difference", each 
            if [Employee Group] = "New Hire" then null 
                else if t[Comp Ratio]{1} > t[Comp Ratio]{0}
                   then t[Comp Ratio]{1} - t[Comp Ratio]{0}
            else null,Percentage.Type), type table[Job Level=Int64.Type, Comp Ratio=Percentage.Type, Difference=Percentage.Type]}
            }),
    #"Expanded Difference" = Table.ExpandTableColumn(#"Grouped Rows", "Difference", 
         {"Comp Ratio", "Difference"})
in
    #"Expanded Difference"

结果与您的数据

M 重现上面的代码table

let
    Source = Table.FromRows(Json.Document(Binary.Decompress(Binary.FromText("i45WMlbSUXKtyCwuycxLBzINDSz0DAxUlWJ1IFJ+qeUKHplFqUCmAVzCBF2POYoUkh5DQ4QuU3RdJihSyLoMjCFSsQA=", BinaryEncoding.Base64), Compression.Deflate)), let _t = ((type nullable text) meta [Serialized.Text = true]) in type table [#"Job Level" = _t, #"Employee Group" = _t, #"Comp Ratio" = _t]),
    #"Previous Step" = Table.TransformColumnTypes(Source,{
        {"Job Level", Int64.Type}, 
        {"Employee Group", type text}, 
        {"Comp Ratio", Percentage.Type}}),

//Add this to your code
    #"Grouped Rows" = Table.Group(#"Previous Step", {"Job Level"}, {
        {"Difference", (t)=> Table.AddColumn(t,"Difference", each 
            if [Employee Group] = "New Hire" then null 
                else if t[Comp Ratio]{1} > t[Comp Ratio]{0}
                   then t[Comp Ratio]{1} - t[Comp Ratio]{0}
            else null,Percentage.Type), type table[Job Level=Int64.Type, Comp Ratio=Percentage.Type, Difference=Percentage.Type]}
            }),
    #"Expanded Difference" = Table.ExpandTableColumn(#"Grouped Rows", "Difference", 
         {"Comp Ratio", "Difference"})
in
    #"Expanded Difference"