📜  for loop dax powerbi increment var (1)

📅  最后修改于: 2023-12-03 15:00:49.961000             🧑  作者: Mango

For Loop in DAX in Power BI

In DAX (Data Analysis Expressions), a for loop is a control flow statement that allows you to execute a block of code repeatedly for a fixed number of iterations. In Power BI, for loops can be used to perform calculations or transformations on large datasets, or to create custom aggregations in a tabular data model.

Syntax

The syntax for a for loop in DAX is as follows:

FOR <counter_variable_name> = <start_value> [, <end_value>] [, <step_value>]
RETURN [<expression>]
  • <counter_variable_name>: The name of the variable used to store the current iteration count.
  • <start_value>: The starting value of the counter.
  • <end_value>: Optional. The ending value of the counter. If not specified, the loop will continue indefinitely.
  • <step_value>: Optional. The value to increment the counter by on each iteration. Defaults to 1.
  • <expression>: The expression to be evaluated for each iteration of the loop. This can be any valid DAX expression.
Example

Let's say we have a table called Sales with columns for Date, Product, and Revenue. We want to create a new table that shows the total revenue for each product over the past 7 days. We can use a for loop to iterate over each product and calculate the sum of revenue for the past 7 days:

Sales 7-Day Total =
VAR LastDate = MAX(Sales[Date])
RETURN
    SUMX(
        FILTER(Sales, Sales[Date] >= LastDate - 7),
        IF(Sales[Product] = PRODUCT_NAME,
           Sales[Revenue],
           0
        )
    )
    FOR PRODUCT_NAME IN VALUES(Sales[Product])

In this example, we use the VALUES function to create a list of all distinct product names in the Sales table. We then use a for loop to iterate over each product name, and within the loop, we use the FILTER function to select only the rows where the Date is within the past 7 days for that product. The SUMX function then calculates the sum of revenue for those selected rows.

Conclusion

The for loop is a powerful tool in DAX that allows you to iterate over large datasets and perform complex calculations. By understanding the syntax and examples provided, you can use for loops to create custom tables and aggregations in Power BI.