强大的查询:将单元格中的表传递给自定义函数

时间:2018-12-09 15:29:12

标签: powerbi powerquery m

我对Power Query中的自定义函数很陌生。 我已经创建了这个。其目的是添加一个自定义列,其内容和名称均基于其获取的参数。我将其保存为 fnCompactedExamples

let

    CompactedExamples = (BaseTable as table, ExamplesTable as table, ExampleNumber as text) =>

        let
            Source = BaseTable,
            #"Add example column" = Table.AddColumn( Source, "sb" & ExampleNumber, each Table.Column( ExamplesTable, Campaign & "_b" & ExampleNumber & "_example")),
            #"Extracted values" = Table.TransformColumns(#"Add example column", { "sb" & ExampleNumber, each Text.Combine(List.Distinct(List.Transform(_, Text.From)), "#(lf)"), type text} )
        in
            #"Extracted values"

in
     CompactedExamples

此函数在以下查询中调用:

let
    Source = #"raw entities table",
    #"Group by cny ID and Cny" = Table.Group(Source, {"Company ID", "Company"}, {{"Data", each _, type table}}),
    #"create sb1 column" = fnCompactedExamples(#"Group by cny ID and Cny", [Data], "1")
in
    #"create sb1 column"

这是“按Cny ID和Cny分组”阶段中表的外观

Table

但是在“创建sb1列”阶段,我得到一个错误:“ Expression.Error:存在一个未知的标识符。您是否在[each]表达式之外使用了[field]的缩写形式_ [field] ?”

我快要走到尽头了,我的错误是一些小细节。我在网上搜寻了有关案件的提示,但找不到任何提示。谁能告诉我那细节吗?

根据@Olly的请求进行编辑:

第二个参数ExamplesTable,实际上是一个表,其中包含我要连接的列,没有任何重复: input table

我的目的是建立一个这样的表,但是现在我使用一系列非常重复的指令: output table

1 个答案:

答案 0 :(得分:0)

这是一个稍微简单的解决方案,它取消显示“示例”列,对其进行适当的重命名,然后再次进行透视,在输出中组合不同的值:

let
    Source = Table1,
    #"Unpivoted Other Columns" = Table.UnpivotOtherColumns(Source, {"Company ID", "Company"}, "Attribute", "Value"),
    #"Renamed Attributes" = Table.TransformColumns(#"Unpivoted Other Columns", {{"Attribute", each "s" & Text.BetweenDelimiters(_, "_", "_"), type text}}),
    #"Pivoted Column" = Table.Pivot(#"Renamed Attributes", List.Distinct(#"Renamed Attributes"[Attribute]), "Attribute", "Value", each Text.Combine(List.Distinct(_),", "))
in
    #"Pivoted Column"

然后您可以进行调整以适合-例如,这将删除空白值,对每个列表进行排序,并使用换行符分隔值:

let
    Source = Table1,
    #"Unpivoted Other Columns" = Table.UnpivotOtherColumns(Source, {"Company ID", "Company"}, "Attribute", "Value"),
    #"Removed Empty Values" = Table.SelectRows(#"Unpivoted Other Columns", each [Value] <> null and [Value] <> ""),
    #"Renamed Attributes" = Table.TransformColumns(#"Removed Empty Values", {{"Attribute", each "s" & Text.BetweenDelimiters(_, "_", "_"), type text}}),
    #"Sorted Attributes" = Table.Sort(#"Renamed Attributes",{{"Attribute", Order.Ascending}}),
    #"Pivoted Column" = Table.Pivot(#"Sorted Attributes", List.Distinct(#"Sorted Attributes"[Attribute]), "Attribute", "Value", each Text.Combine(List.Sort(List.Distinct(_)),"#(lf)"))
in
    #"Pivoted Column"