15.12.2020 Views

Beginning DAX with Power BI_ The SQL Pro’s Guide to Better Business Intelligence ( PDFDrive )

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 2

Variables

You can use this technique with other DAX functions to create dynamic text-based

measures that may change depending on the current filter context. Consider the

following calculated measure:

Sales Text =

VAR SalesQty = SUM('Fact Sale'[Quantity])

VAR Text1 = "This month we sold "

VAR Text2 = " Items"

VAR Result = IF(

SalesQty > 0,

-- THEN --

Text1 & SalesQty & Text2,

-- ELSE --

"No sales this month"

)

RETURN Result

Here you assign the DAX SUM expression to the SalesQty variable. This is used later

in the IF function to test for the existence of sales to determine the output message. Note

the use of comments in the IF function to help clarify which code is being used to update

the Result variable.

This also shows how you can use variables to improve performance. The SalesQty

variable is potentially used twice in the IF function. If this formula was written without

using variables, the IF function would make two calls to the underlying column and

therefore take longer to arrive at the same result.

A similar function using text-based variables is one that generates a greeting

calculated measure. Creating a calculated measure using the code in Listing 2-1 tests

the current time of day and stores the hour of the day in the CurrentHour variable.

This is then used in a SWITCH function to generate appropriate text to be stored in the

GreetingText variable. This is then combined with other text to produce a measure that

you can use as a dynamic greeting on your report.

30

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!