用函数或循环简化这个DAX?

时间:2018-03-08 17:11:00

标签: powerbi dax

我有一个非常冗长的代码,它构建了一个计算的不透明数据表(另一个表有计算字段,所以我不能通过M取消它。)有没有办法删除我的所有重复代码DAX?代码是一致的,除了两个点,我需要插入一个唯一的值。例如,在SELECTCOLUMNS的第一部分中,唯一的唯一值是ATL,在第二部分是Austin。

UNION(
    FILTER(
        SELECTCOLUMNS(
            MetroSalesData_Table,
            "LOCATION", "ATL",
            "ZIP", MetroSalesData_Table[Zip],
            "COVERAGE", MetroSalesData_Table[_ATL],
            "CUSTOMER", MetroSalesData_Table[Customer Name],
            "TRADE (BROAD)", MetroSalesData_Table[Miner Trade Broad],
            "TRADE (GROUP)", MetroSalesData_Table[Miner Trade Group],
            "TRADE (TYPE)", MetroSalesData_Table[Miner Trade Type],
            "TRADE (METRO)", MetroSalesData_Table[Trade],
            "COGS", MetroSalesData_Table[COGS],
            "SALES", MetroSalesData_Table[Revenue]
        ), [COVERAGE] = "Area coverage only" || [COVERAGE] = "YES"
    ),
    FILTER(
        SELECTCOLUMNS(
            MetroSalesData_Table,
            "LOCATION", "Austin",
            "ZIP", MetroSalesData_Table[Zip],
            "COVERAGE", MetroSalesData_Table[_Austin],
            "CUSTOMER", MetroSalesData_Table[Customer Name],
            "TRADE (BROAD)", MetroSalesData_Table[Miner Trade Broad],
            "TRADE (GROUP)", MetroSalesData_Table[Miner Trade Group],
            "TRADE (TYPE)", MetroSalesData_Table[Miner Trade Type],
            "TRADE (METRO)", MetroSalesData_Table[Trade],
            "COGS", MetroSalesData_Table[COGS],
            "SALES", MetroSalesData_Table[Revenue]
        ), [COVERAGE] = "Area coverage only" || [COVERAGE] = "YES"
    ),
    FILTER(...

1 个答案:

答案 0 :(得分:0)

如果您的MetroSalesData_Table有一个唯一的索引列,那么您可以使用这样的方法(我将使用下面的名称MetroSales来节省空间):

ADDCOLUMNS(
    FILTER(
        UNION(SELECTCOLUMNS(MetroSales,
                            "LOCATION", "ATL",
                            "COVERAGE", MetroSales[_ATL],
                            "Index", MetroSales[Index]),
              SELECTCOLUMNS(MetroSales,
                            "LOCATION", "Austin",
                            "COVERAGE", MetroSales[_Austin],
                            "Index", MetroSales[Index]),
              SELECTCOLUMNS([...])),
        [COVERAGE] = "Area coverage only" || [COVERAGE] = "YES"),
    "ZIP", LOOKUPVALUE(MetroSales[Zip], MetroSales[Index], [Index]),
    "CUSTOMER", LOOKUPVALUE(MetroSales[Customer Name], MetroSales[Index], [Index]),
    [...]
    "SALES", LOOKUPVALUE(MetroSales[Revenue], MetroSales[Index], [Index]))

基本上,我们使用UNION取消,添加过滤器,然后使用索引在原始表中查找其他列。

如果原始表没有唯一索引,则可以使用添加列>在查询编辑器中添加一个(推荐)。索引列或者沿着以下行写下计算列:

Index = RANKX(ALL(MetroSales),
              MetroSales[Customer Name] & MetroSales[Zip],
              , ASC, Dense)

(如果名称和zip组合在表格中不唯一,则根据需要在上面的中间行添加更多列名称。)