Code Explainer | DAX

DAX Analysis for Pest Control Metrics

This document provides a detailed breakdown of a DAX code snippet used in Power BI to analyze pest control activities. It highlights variable definitions, key components, and the final result calculation, showcasing data manipulation and


Empty image or helper icon

Prompt

VAR LogicTest =
    CALCULATE (
        COUNTROWS ( 'TimePeriodslicer' ),
        KEEPFILTERS ( 'TimePeriodslicer' )
    )
VAR OrdersWithCatches =
    CALCULATETABLE (
        VALUES ( 'Scan Pest'[ServiceOrderKey] ),
        KEEPFILTERS ( 'Scan Pest'[CatchPestQuantity] > 0 ),
        ALLSELECTED ( 'Date' ),
        ALLSELECTED ( 'Date Translation' )
    )
/* Order/Eqiupment pair of catches */    
VAR OrderEqiupmentWithCatches = 
        DISTINCT(
            SUMMARIZE(  CALCULATETABLE 
(
                                 'Scan Pest',
                                KEEPFILTERS ( 'Scan Pest'[CatchPestQuantity] > 0 ),
                                ALLSELECTED ( 'Date' ),
                                ALLSELECTED ( 'Date Translation' )
                            ),
                        'Scan Pest'[ServiceOrderKey], 
                         'Scan Pest'[CurrentEquipmentLocationDimKey]) 

    )
/* Negative of Order/Eqiupment pair of catches */
VAR OrderEquipmentWithoutCatches = 
        DISTINCT(
            SUMMARIZE(  CALCULATETABLE (
                                 'Scan Pest',
                                KEEPFILTERS ( 'Scan Pest'[CatchPestQuantity] 
= 0 ),
                                ALLSELECTED ( 'Date' ),
                                ALLSELECTED ( 'Date Translation' )
                            ),
                        'Scan Pest'[ServiceOrderKey], 
                         'Scan Pest'[CurrentEquipmentLocationDimKey]) 

    )
VAR OrdersWithIsPestActivity =
    CALCULATETABLE (
        VALUES ( 'Scan Status'[ServiceOrderKey] ),
        KEEPFILTERS ( 'Scan Pest'[PestQuantity] > 0 ),
        KEEPFILTERS ( 'Global Status'[IsPestActivity] = TRUE () ),
        ALLSELECTED ( 'Date' ),
        ALLSELECTED ( 'Date Translation' 
)
    )
VAR OrderEquipmentWithIsPestActivity = 
        DISTINCT(
            SUMMARIZE(  CALCULATETABLE (
                         'Scan Status' ,
                        KEEPFILTERS ( 'Scan Pest'[PestQuantity] > 0 ),
                        KEEPFILTERS ( 'Global Status'[IsPestActivity] = TRUE () ),
                        ALLSELECTED ( 'Date' ),
                        ALLSELECTED ( 'Date Translation' )
                            ),
                        'Scan Status'[ServiceOrderKey], 
                        'Scan Status'[CurrentEquipmentLocationDimKey]) 

    )
VAR AllOrdersCatchesIsPestActivity =
   
 UNION(OrdersWithCatches,OrdersWithIsPestActivity)
VAR CountCatches =
    CALCULATE (
        [Total Catches],
        KEEPFILTERS ( 'Service Order Attributes'[ServiceOrderKey] IN ( OrdersWithCatches ) )
    )
VAR TotalCountAlertEvents =
    CALCULATE (
        [Confirmed Alert Count],
        KEEPFILTERS ( 'Service Order Attributes'[ServiceOrderKey] IN ( AllOrdersCatchesIsPestActivity ) ),
        ALLSELECTED ( 'Date' ),
        ALLSELECTED ( 'Date Translation' )
    )
/* Only service order & equipment pair witht 'Scan pest'[PestQuanity] > 0, 'Global Status'[IsPestActivity] = True() and NOT service order &
   equipment pair that has a Catch */
VAR 
TotalCountPestActivity =
    CALCULATE (
        [Total Pest Quantity Pressure],
        //[IsPestActivity Scan Count],
        KEEPFILTERS ( 'Service Order Attributes'[ServiceOrderKey] IN ( AllOrdersCatchesIsPestActivity ) ),
        TREATAS(OrderEquipmentWithIsPestActivity, 'Scan Pest'[ServiceOrderKey], 'Scan Pest'[CurrentEquipmentLocationDimKey]),
        TREATAS(OrderEquipmentWithoutCatches, 'Scan Pest'[ServiceOrderKey], 'Scan Pest'[CurrentEquipmentLocationDimKey]),
        ALLSELECTED ( 'Date' ),
        ALLSELECTED ( 'Date Translation' )
    )
VAR CountAlertEvents =
    CALCULATE (
        [Confirmed Alert Count],
        KEEPFILTERS ( 'Service Order Attributes'[ServiceOrderKey] IN ( OrdersWithIsPestActivity ) )
    )
VAR CountPestActivity =
    CALCULATE (
        [Total Pest Quantity Pressure],
        //[IsPestActivity Scan Count],
        KEEPFILTERS ( 'Service Order Attributes'[ServiceOrderKey] IN (OrdersWithIsPestActivity  ) ),
        TREATAS(OrderEquipmentWithIsPestActivity, 'Scan Pest'[ServiceOrderKey], 'Scan Pest'[CurrentEquipmentLocationDimKey]),
        TREATAS(OrderEquipmentWithoutCatches, 'Scan Pest'[ServiceOrderKey], 'Scan Pest'[CurrentEquipmentLocationDimKey])        
    )
VAR Result = CountCatches +
    if( TotalCountAlertEvents >= TotalCountPestActivity, CountAlertEvents,  0) + 
    if( TotalCountPestActivity > TotalCountAlertEvents, CountPestActivity ,  0)
    +  0
RETURN
    IF ( LogicTest > 0, Result, BLANK () )

Answer

Breakdown of the Given Code Snippet

The provided code snippet is written in DAX (Data Analysis Expressions), which is primarily used within platforms like Power BI and SQL Server Analysis Services for data analysis and calculations. The code includes multiple variables and calculations that aggregate and filter data related to pest activities and service orders.

Section 1: Introduction to Variables

The code uses several VAR statements to define reusable expressions, making the code modular and easier to read. Each variable is defined to encapsulate specific logic or calculations.

Example Variables:

  • LogicTest: This variable counts the rows from the 'TimePeriodslicer' table but applies any filters from the slicer context.
  • OrdersWithCatches: This retrieves distinct service order keys where the quantity of "Catch Pest" is greater than zero.

Section 2: Key Components of the Code

2.1 LogicTest

VAR LogicTest =
    CALCULATE (
        COUNTROWS ( 'TimePeriodslicer' ),
        KEEPFILTERS ( 'TimePeriodslicer' )
    )
  • CALCULATE: This function evaluates an expression in a modified filter context.
  • COUNTROWS: Counts the number of rows in the specified table.
  • KEEPFILTERS: Maintains the existing filters on the specified table, ensuring the row count only considers the filtered context.

2.2 OrdersWithCatches

VAR OrdersWithCatches =
    CALCULATETABLE (
        VALUES ( 'Scan Pest'[ServiceOrderKey] ),
        KEEPFILTERS ( 'Scan Pest'[CatchPestQuantity] > 0 ),
        ALLSELECTED ( 'Date' ),
        ALLSELECTED ( 'Date Translation' )
    )
  • CALCULATETABLE: Returns a table that has been modified by the provided filters.
  • VALUES: Returns a one-column table that contains the distinct values from the specified column.
  • ALLSELECTED: Removes filters from the specified columns or tables, while retaining the filters applied by the user interface selections.

2.3 OrderEqiupmentWithCatches

VAR OrderEquipmentWithCatches = 
    DISTINCT(
        SUMMARIZE(  
            CALCULATETABLE (
                'Scan Pest',
                KEEPFILTERS ( 'Scan Pest'[CatchPestQuantity] > 0 ),
                ALLSELECTED ( 'Date' ),
                ALLSELECTED ( 'Date Translation' )
            ),
            'Scan Pest'[ServiceOrderKey], 
            'Scan Pest'[CurrentEquipmentLocationDimKey]
        )
    )
  • DISTINCT: This function removes duplicate values from the resulting table.
  • SUMMARIZE: Creates a summary table for the specified grouping columns and their aggregations.

2.4 TotalCountPestActivity

VAR TotalCountPestActivity =
    CALCULATE (
        [Total Pest Quantity Pressure],
        KEEPFILTERS ( 'Service Order Attributes'[ServiceOrderKey] IN ( AllOrdersCatchesIsPestActivity ) ),
        TREATAS(OrderEquipmentWithIsPestActivity, 'Scan Pest'[ServiceOrderKey], 'Scan Pest'[CurrentEquipmentLocationDimKey]),
        TREATAS(OrderEquipmentWithoutCatches, 'Scan Pest'[ServiceOrderKey], 'Scan Pest'[CurrentEquipmentLocationDimKey]),
        ALLSELECTED ( 'Date' ),
        ALLSELECTED ( 'Date Translation' )
    )
  • TREATAS: Used to apply the filters from one table to another. This is critical when matching service orders to equipment locations.
  • [Total Pest Quantity Pressure]: Refers to a previously defined measure, which likely calculates the cumulative quantity of pests.

Section 3: Final Result Calculation

VAR Result = CountCatches +
    IF( TotalCountAlertEvents >= TotalCountPestActivity, CountAlertEvents,  0) + 
    IF( TotalCountPestActivity > TotalCountAlertEvents, CountPestActivity , 0)

This section combines the individual counts of catches, alert events, and pest activities to yield the final result.

Logic Explanation:

  • The Result variable aggregates:
    • Total catches
    • Conditional additions based on comparisons between alert event counts and pest activity counts.

Final RETURN Statement

RETURN
    IF ( LogicTest > 0, Result, BLANK () )
  • RETURN: This concludes the definition of the measure.
  • IF: This checks if LogicTest is greater than zero before returning the result. If not, it outputs BLANK() to avoid cluttering report visuals with irrelevant data.

Section 4: Conclusion

The provided DAX code is a robust example of a calculation within a business intelligence context, focusing on pest control activities and their associated metrics. Each variable encapsulates specific logic, and together they create a comprehensive measure that can be analyzed in reporting tools. By using functions such as CALCULATE, VALUES, and SUMMARIZE, the code efficiently manages data manipulation and context filtering necessary for accurate reporting.

For those looking to deepen their understanding of DAX and its application in data analysis, engaging with courses offered on the Enterprise DNA Platform could be beneficial.

Create your Thread using our flexible tools, share it with friends and colleagues.

Your current query will become the main foundation for the thread, which you can expand with other tools presented on our platform. We will help you choose tools so that your thread is structured and logically built.

Description

This document provides a detailed breakdown of a DAX code snippet used in Power BI to analyze pest control activities. It highlights variable definitions, key components, and the final result calculation, showcasing data manipulation and context filtering techniques.