在power bi中添加计算列(从同一表中计算)

时间:2017-07-25 05:43:26

标签: powerbi

Table

我有上表:

该表可以有多个相同ID的记录(标题将不同)

现在我需要添加一个计算列"父标题"。 因此,如果父ID为1,则父标题应为id 1的最后标题(标题11)。 如果父ID是2,则父标题应该是id 2的最后标题(标题22)。 如果父ID为BLANK,则父标题应为BLANK。

我怎样才能实现这个目标?

2 个答案:

答案 0 :(得分:1)

可能有 clean 方式,但我可以通过Power Query获取此信息:

enter image description here

以下是:

我从你的桌子开始(我称之为Table1):

enter image description here

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

enter image description here

然后我将Table2转换为以下内容。 (我先做了一些排序,然后是其他一些“有趣的东西。”你可以看到我在M代码中所做的一切。)

enter image description here

这是表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代码并将其粘贴到Table2查询中的初始代码中,该查询是在“参考”期间在“高级编辑器”中生成的...)

enter image description here

然后我使用Table2作为创建Table3的源代码。 (我再次使用“参考”。)

enter image description here

Table3的M代码非常简单:

let
Source = Table2
in
Source

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

enter image description here

enter image description here

(注意我将Table2中的LesserMaxIndex与Table3中的MaxIndex匹配并使用了Left Outer连接。)

我将合并后的查询命名为“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"

答案 1 :(得分:0)

使用

行的Excel工作表公式相当容易
=IF(Table1[@[Parent ID]]="","",INDEX(B:B,MATCH(Table1[@[Parent ID]],A:A,1)))

就其本质而言,PowerPivot / Power BI的语言(即DAX)没有像Index / Match或Vlookup这样的内容,因为这样的结构是通过关联表来完成的。

如果您处于想要计算类似内容的情况,那么重新评估数据架构可能是明智之举。创建另一个查询,加载您的初始表,对其进行排序,删除重复的ID,并只保留您想要的。然后,您可以使用Power Pivot中的关系,或使用查询与原始数据表合并。

相关问题