在 power bi 中添加计算列(从相同 table 计算)

adding calculated column in power bi (calculated from same table)

我有上面的table:

table同一个id可以有多个记录(标题会不同)

现在我需要添加一个计算列 "Parent Title"。 因此,如果 parent id 为 1,则 parent title 应该是 id 1 的最后一个标题(Title 11)。 如果 parent id 是 2,那么 parent title 应该是 id 2 的最后一个标题(Title 22)。 如果 parent id 为空,则 parent 标题应为空。

我怎样才能做到这一点?

使用 Excel 工作表公式按照

行可以很容易地做到这一点
=IF(Table1[@[Parent ID]]="","",INDEX(B:B,MATCH(Table1[@[Parent ID]],A:A,1)))

就其本质而言,PowerPivot/Power BI 的语言,即 DAX,没有类似 Index/Match 或 Vlookup 的东西,因为此类构造是通过关联 table 完成的。

如果您想要计算类似的东西,重新评估您的数据架构可能是明智的。创建另一个查询来加载您的初始 table,对其进行排序,删除重复的 ID 并仅保留您想要的 ID。然后您可以在 Power Pivot 中使用关系或使用查询与原始数据合并 table.

可能有一种 cleaner 方法可以做到这一点,但我能够通过 Power Query 获得它:

方法如下:

我从你的 table 开始(我称之为表 1):

然后我使用 Table1 作为创建 Table2 的来源。 (我使用 "Reference" 来做到这一点:我右键单击 Table1 并从下拉列表中选择 "Reference"。)

然后我把Table2改成了下面这样。 (我先做了一些排序,然后做了一些其他的 "fun stuff." 你可以看到我在 M 代码中做了什么。)

这是表 2 的 M 代码:

let
Source = Table1,
#"Sorted Rows" = Table.Sort(Source,{{"Id", Order.Ascending}, {"title", Order.Ascending}, {"Parent Id", Order.Ascending}}),
#"Added Index" = Table.AddIndexColumn(#"Sorted Rows", "Index", 1, 1),
#"Grouped Rows" = Table.Group(#"Added Index", {"Id"}, {{"MinIndex", each List.Min([Index]), type number}, {"MaxIndex", each List.Max([Index]), type number}, {"AllData", each _, type table}}),
#"Expanded AllData" = Table.ExpandTableColumn(#"Grouped Rows", "AllData", {"title", "Parent Id", "Index"}, {"title", "Parent Id", "Index"}),
#"Added Custom" = Table.AddColumn(#"Expanded AllData", "MaxTitle", each if [MaxIndex]=[Index]then[title]else null),
#"Filled Up" = Table.FillUp(#"Added Custom",{"MaxTitle"}),
#"Added Custom1" = Table.AddColumn(#"Filled Up", "LesserMaxIndex", each [MinIndex]-1)
in
#"Added Custom1"

(您可以复制上面的 M 代码并将其粘贴到 "Reference" 期间生成的 Table2 查询中的初始代码,在 "Advanced Editor"...)

然后我使用 Table2 作为创建 Table3 的来源。 (我又用了"Reference"。)

Table3的M代码很简单:

let
Source = Table2
in
Source

最后,我使用 "Home" 选项卡上的 "Merge Queries" 合并了 Table2 和 Table3。具体来说,我使用了 "Merge Queries as New".

(请注意,我将 Table2 中的 LesserMaxIndex 与 Table3 中的 MaxIndex 进行了匹配,并使用了左外连接。)

我将合并查询命名为 "Merge1"。

然后我对 Merge1 做了一些清理,您可以在 M 代码中看到:

let
Source = Table.NestedJoin(Table2,{"LesserMaxIndex"},Table3,{"MaxIndex"},"Table1 (4)",JoinKind.LeftOuter),
#"Expanded Table1 (4)" = Table.ExpandTableColumn(Source, "Table1 (4)", {"MaxTitle"}, {"ParentTitle"}),
#"Sorted Rows" = Table.Sort(#"Expanded Table1 (4)",{{"Id", Order.Ascending}, {"title", Order.Ascending}, {"Parent Id", Order.Ascending}}),
#"Removed Duplicates" = Table.Distinct(#"Sorted Rows"),
#"Removed Other Columns" = Table.SelectColumns(#"Removed Duplicates",{"Id", "title", "Parent Id", "ParentTitle"})
in
#"Removed Other Columns"