Power BI DAX Tutorial for Beginners

Page 1

Power BI DAX Tutorial for Beginners

What is DAX?

DAXorDataAnalysisExpressionsdriveallthecalculationsyoucanperforminPower BI.DAXformulasareversatile,dynamic,andverypowerful—theyallowyoutocreate newfieldsandevennewtablesinyourmodel.WhileDAXismostcommonly associatedwithPowerBI,youcanalsofindDAXformulasinPowerPivotinExceland SQLServerAnalysisServices(SSAS).

DAXformulasaremadeupof3corecomponentsandthistutorialwillcovereachof these: Syntax—ProperDAXsyntaxismadeupofavarietyofelements,someofwhichare commontoallformulas.

Functions DAXfunctionsarepredefinedformulasthattakesomeparameters andperformaspecificcalculation.

Context DAXusescontexttodeterminewhichrowsshouldbeusedtoperforma calculation.

Why is DAX Important in Power BI?

DAXformulasallowyoutogetthemostoutofyourdataandPowerBIinordertosolve businessproblemsefficiently.Youcanperformsimplecalculations(suchasasimple sumoraverage)andcreatemostvisualswithouteventouchingDAX.Forexample,if youwantedtocreateasimplechartshowingtotalprofityoucouldsimplydragthe

/1 /2 , :3 , ://m .c /p /b / Itexamtools Sep 28 · 7 min read · Listen Save
16 Get unlimited access Open in app

profitfieldontotheValuessectionofthechart,anditwouldperformasumofthe rowsinthatfield.

TherearetwocaseswhereitwouldbebettertocreateaDAXformula:

1.Ifyouwantedtore useaformulainmultipleplaces,suchasinmultiplechartsor asanexpressioninotherDAXformulas.Inthiscase,usingaDAXformulawould makeyourreportmoreefficientandeasiertochangeinthefuturesinceyouwould onlyneedtochangeasingleformularatherthanchangingmanyindividual formulasineachplacetheyareused.

2.IfyouwantedtocreatecomplexorcustomizedformulaswherejustasimpleSUM orAVERAGEwouldnotbesufficientforthebusinessproblemyouweretryingto solve.

Where are DAX Formulas Used in Power BI?

TherearethreewaysyoucanuseDAXformulasinPowerBI:

1.CalculatedTables

Thesecalculationswilladdanadditionaltabletothereport basedonaformula.

2.CalculatedColumns—Thesecalculationswilladdanadditionalcolumntoatable basedonaformula.Thesecolumnsaretreatedlikeanyotherfieldinthetable.

3.Measures Thesecalculationswilladdasummaryoraggregatedmeasuretoa tablebasedonaformula.

Themaindifferencebetweenthesethreetypesofcalculationsisintheircontext(more onthislater)andtheoutputstheyproduce.

Toaddanyoneofthesetypesofcalculationstoamodel,navigatetotheModelingtab oftheribbon.Hereyouwillfindthreechoicesforaddingeitheranewmeasure, calculatedcolumn,ortable.Alternatively,youcanright clickatableintheFieldspane, andyouwillgettheoptiontoaddanewmeasureorcalculatedcolumninthedrop downmenu.

/1 /2 , :3 , ://m .c /p /b /
Get unlimited access Open in app
/1 /2 , :3 , ://m .c /p /b / How to Write a DAX Formula DAXformulasareintuitiveandeasytoread.Thismakesiteasytounderstandthe basicsofDAXsoyoucanstartwritingyourownformulasrelativelyquickly.Let’sgo overthebuildingblocksofproperDAXsyntax. 1.Thenameofthemeasureorcalculatedcolumn 2.Theequal tooperator(“=”)indicatesthestartoftheformula 3.ADAXfunction 4.Opening(andclosing)parentheses(“()”) 5.Columnand/ortablereferences 6.Notethateachsubsequentparameterinafunctionisseparatedbyacomma(“,”) DAXfunctionscanalsobenestedinsideeachothertoperformmultipleoperations efficiently.ThiscansavealotoftimewhenwritingDAXformulas.Forexample itis Get unlimited access Open in app

oftenusefultohavemultiplenestedIFstatementsortousetheIFERRORfunctionto wraparoundanotherfunction,sothatanyerrorsintheformulaarerepresentedbythe valueyouspecify.

SomeofthemostcommonDAXfunctionsusedinreportsare:

1.Simplecalculations:COUNT,DISTINCTCOUNT,SUM,AVERAGE,MIN,MAX.

2.SUMMARISE:Returnsatabletypicallyusedtofurtherapplyaggregationsover differentgroupings.

3.CALCULATE:Performsanaggregationalongwithoneormorefilters.Whenyou specifymorethanonefilter,thefunctionwillperformthecalculationwhereall filtersaretrue.

4.IF:Basedonalogicalcondition,itwillreturnadifferentvalueforifitistrueor false.ThisissimilartotheCASEWHENoperationinSQL.

5.IFERROR:Looksforanyerrorsforaninnerfunctionandreturnsaspecifiedresult

6.ISBLANK:Checksiftherowsinacolumnareblankandreturnstrueorfalse. UsefultouseinconjunctionwithotherfunctionslikeIF.

7.EOMONTH:Returnsthelastdayofthemonthofagivendate(columnreferencein adateformat)forasmanymonthsinthepastorthefuture.

8.DATEDIFF:returnsthedifferencebetween2dates(bothascolumnreferencesin dateformats)indays,months,quarters,years,etc.

Understanding Context in DAX Formulas

DAXformulasinPowerBIaredynamic,andtheychangeaccordingtothecontextin whichtheywerecreated.It’simportanttohaveanunderstandingofhowcontextswork inDAX,asitcanhelpsaveyoualotofheadacheswhenyourunintoconfusingerrors inyourformulas.

TherearetwomaintypesofcontextinDAX:rowcontextandfiltercontext.

Row Context

/1 /2 , :3 , ://m .c /p /b /
Get unlimited access Open in app

Thisreferstojust“thecurrentrow”acrossallcolumnsofatableandalsoextendstoall columnsinrelatedtablestoo.ThistypeofcontextletstheDAXformulaknowwhich rowstouseforaspecificformula.

Hereisanexampleofaformulaforacalculatedcolumnthathasarowcontext:

Cost Price Per Unit =

Inthisexample,thecalculationofCostPricePerUnitisdoneonarowbyrowbasis. ThismeansthatDAXneedstoknowwhatthecurrentrowisasitproceedsthroughthe dataset,makingthecalculationandpopulatingthenewcolumnwiththeresult.

Rowcontextisimplicitincalculatedcolumns.Thisisbecausethecalculationsthatare performedincalculatedcolumnsaredoneonarowbyrowbasis,andthustherow contextisdefinedbydefault.However,thisisnotthecaseinmeasuressincethe aggregationsareappliedforallrowsinatable.Thesecalculationsdonotneedtohave anyknowledgeofacurrentrowsinceallrowsareaggregatedtogether.

Asanexampleofameasure,considerthefollowingDAXformula:

Profit margin = SUM (

Inthiscase,theentireProfitcolumnissummedtoproduceasinglenumber,andthis isdividedbythesumoftheentireSalescolumn.DAXdoesnotneedtoknowthe

/1 /2 , :3 , ://m .c /p /b /
financials[COGS] / financials[Units Sold]
financials[Profit] ) / SUM ( financials[Sales] )
Get unlimited access Open in app

currentrow,sinceitisperforminganaggregation.Thus,thismeasurehasnorow context.

Toexplicitlydefinearowcontextinameasure,youneedtouseaspecialfunction calledaniterator.ExamplesofiteratorfunctionsareSUMX,AVERAGEX,andCOUNTX. Thesefunctionswillfirstperformacalculationonarowbyrowbasis,andthen performthefinalaggregationontheresult(ie.sum,average,count,etc.).Inthisway, therowcontextisdefinedexplicitlybytheuseoftheseiterators.

Let’stakealookatanexampleofaniteratorfunctioninaction:

Average Cost Per Unit = AVERAGEX ( financials, financials[COGS] / financials[Units Sold] )

Thisexampleperformstwocalculations:first,theexpressionisevaluatedonarowby rowbasis,andthentheresultisappliedtotheAVERAGEfunction.Analternativeway ofreachingthissameresultistofirstcreatethecalculatedcolumn‘CostPricePerUnit’ aswedidaboveandthencreateaseparateAVERAGEmeasureofthatcolumn. However,knowingwhentousetheseiteratorfunctionscanmakeyourreportsmore efficientanduseuplessmemoryasyouareeffectivelyabletoperformtwo calculationsusingjustasingleformula.

Filter Context

Filtercontextisappliedontopofarowcontextandreferstoasubsetofrowsor columnsthatarespecifiedasfiltersinthereport.Filterscanbeappliedinafewways:

DirectlyinaDAXformula

Throughthefieldsthatmakeupavisual(suchastherowsandcolumnsina matrix)

AgoodexampleofhowtoaddafiltercontexttoaDAXformulaistousethe CALCULATEfunction,whichallowsyoutoaddoneormorefilterparameterstothe

/1 /2 , :3 , ://m .c /p /b /
Usingthefilterspane Usingaslicervisual
Get unlimited access Open in app
/1 /2 , :3 , ://m .c /p /b / measure.Intheexamplebelow,wecreateaprofitmarginmeasurefilteredforUSA only: USA Profit Margin = CALCULATE ( SUM ( financials[Profit] ) / SUM ( financials[Sales] ), financials[Country] = "United States of America") Conclusion YounowhavesomebasicDAXtoolstotryout,andtheyarejustthetipoftheicebergof allthatDAXcando. Originallypublishedathttps://itexamsusa.blogspot.com. Get an email whenever Itexamtools publishes. You cannot subscribe to yourself Get unlimited access Open in app

Turn static files into dynamic content formats.

Create a flipbook
Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.