CONNECT:
jonmaas1978 AT gmail DOT com +1-310-500-5841
DAX samples

Here are some DAX samples, searchable by keyword.

CategorySub-categoryDAX Query NameDAX CodeComment on the CodeDescriptionKeywords
AggregationBasicTotal SalesSUM(Sales[Amount])Simple sum aggregationCalculates the total of all sales amountssum total aggregate basic
AggregationBasicAverage PaymentAVERAGE(Payments[Amount])Mean calculationComputes the arithmetic mean of payment amountsaverage mean aggregate
AggregationBasicCount CustomersCOUNT(Customers[CustomerID])Count non-blank valuesCounts the number of non-blank customer IDscount rows records
AggregationBasicCount Distinct ProductsDISTINCTCOUNT(Orders[ProductID])Count unique valuesCounts unique product IDs in orders tabledistinct unique count
AggregationBasicMin TransactionMIN(Transactions[Amount])Minimum valueReturns the smallest transaction amountminimum min lowest
AggregationBasicMax TransactionMAX(Transactions[Amount])Maximum valueReturns the largest transaction amountmaximum max highest
AggregationAdvancedSum Ignore FiltersSUMX(ALL(Sales), Sales[Amount])Sum with ALL functionCalculates sum ignoring current filter contextsumx all ignore filter context
AggregationAdvancedWeighted Average PriceSUMX(Sales, Sales[Quantity] * Sales[Price]) / SUM(Sales[Quantity])SUMX for weighted calculationComputes weighted average using iteratorweighted average sumx iterator
AggregationAdvancedCount All RowsCOUNTROWS(Sales)Count all rows including blanksCounts total rows regardless of blank valuescountrows all rows
AggregationAdvancedCount Rows with FilterCOUNTROWS(FILTER(Sales, Sales[Amount] > 100))Conditional row countCounts rows meeting specific criteriacountrows filter conditional
Time IntelligencePeriod CalculationsYear To Date SalesTOTALYTD(SUM(Sales[Amount]), Calendar[Date])YTD aggregationCalculates year-to-date total salesytd year to date time
Time IntelligencePeriod CalculationsQuarter To Date SalesTOTALQTD(SUM(Sales[Amount]), Calendar[Date])QTD aggregationCalculates quarter-to-date total salesqtd quarter to date
Time IntelligencePeriod CalculationsMonth To Date SalesTOTALMTD(SUM(Sales[Amount]), Calendar[Date])MTD aggregationCalculates month-to-date total salesmtd month to date
Time IntelligencePeriod CalculationsSame Period Last YearCALCULATE(SUM(Sales[Amount]), SAMEPERIODLASTYEAR(Calendar[Date]))Prior year comparisonReturns sales for same period in previous yearsameperiodlastyear prior year py
Time IntelligenceComparisonPrevious Month SalesCALCULATE(SUM(Sales[Amount]), PREVIOUSMONTH(Calendar[Date]))Prior month valueReturns sales for the previous monthpreviousmonth prior month pm
Time IntelligenceComparisonPrevious Year SalesCALCULATE(SUM(Sales[Amount]), PREVIOUSYEAR(Calendar[Date]))Prior year valueReturns sales for the previous yearpreviousyear prior year
Time IntelligenceComparisonYear Over Year GrowthDIVIDE(SUM(Sales[Amount]) – CALCULATE(SUM(Sales[Amount]), SAMEPERIODLASTYEAR(Calendar[Date])), CALCULATE(SUM(Sales[Amount]), SAMEPERIODLASTYEAR(Calendar[Date])))YoY percentage changeCalculates year-over-year growth percentageyoy growth variance comparison
Time IntelligenceComparisonRolling 12 MonthsCALCULATE(SUM(Sales[Amount]), DATESINPERIOD(Calendar[Date], LASTDATE(Calendar[Date]), -12, MONTH))Trailing 12-month totalSum of last 12 months from current daterolling trailing 12 months ttm
Time IntelligenceComparisonLast 30 DaysCALCULATE(SUM(Sales[Amount]), DATESINPERIOD(Calendar[Date], LASTDATE(Calendar[Date]), -30, DAY))Trailing 30-day totalSum of last 30 days from current datelast 30 days trailing
Filter ContextCALCULATESales This YearCALCULATE(SUM(Sales[Amount]), Calendar[Year] = YEAR(TODAY()))Filter by current yearCalculates sales for the current year onlycalculate filter year current
Filter ContextCALCULATEHigh Value SalesCALCULATE(SUM(Sales[Amount]), Sales[Amount] > 1000)Filter by thresholdSums only sales exceeding 1000calculate filter threshold conditional
Filter ContextCALCULATEActive Customer SalesCALCULATE(SUM(Sales[Amount]), Customers[Status] = “Active”)Filter by statusCalculates sales from active customers onlycalculate filter status active
Filter ContextCALCULATEMultiple Filter SalesCALCULATE(SUM(Sales[Amount]), Products[Category] = “Electronics”, Calendar[Year] = 2024)Multiple filter conditionsApplies multiple simultaneous filterscalculate multiple filters and
Filter ContextALL FunctionsRemove All FiltersCALCULATE(SUM(Sales[Amount]), ALL(Sales))Clear all filters on tableCalculates total ignoring all filters on Salesall remove clear filters
Filter ContextALL FunctionsRemove Column FilterCALCULATE(SUM(Sales[Amount]), ALL(Products[Category]))Clear specific column filterIgnores filter on Category column onlyall column filter remove
Filter ContextALL FunctionsKeep Other FiltersCALCULATE(SUM(Sales[Amount]), ALLEXCEPT(Sales, Sales[Region]))Clear all except specifiedRemoves all filters except Region filterallexcept keep preserve
Filter ContextALL FunctionsAll SelectedCALCULATE(SUM(Sales[Amount]), ALLSELECTED(Sales))Respect slicer selectionsRemoves filters but keeps slicer contextallselected slicer visual
Filter ContextFILTER FunctionFiltered SumCALCULATE(SUM(Sales[Amount]), FILTER(Products, Products[Price] > 50))Dynamic filter tableFilters Products table then calculatesfilter table dynamic
Filter ContextFILTER FunctionComplex Filter ConditionCALCULATE(SUM(Sales[Amount]), FILTER(ALL(Customers), Customers[TotalPurchases] > 1000 && Customers[Region] = “West”))Multiple AND conditionsApplies complex multi-condition filterfilter complex and conditions
Filter ContextFILTER FunctionRelated Table FilterCALCULATE(SUM(Sales[Amount]), FILTER(ALL(Calendar), Calendar[Year] = 2024))Filter related tableFilters through relationshipfilter related relationship
Calculated ColumnsBasicFull NameCustomers[FirstName] & ” ” & Customers[LastName]String concatenationCombines first and last name with spaceconcatenate combine string text
Calculated ColumnsBasicProfit MarginDIVIDE(Sales[Profit], Sales[Revenue])Division with error handlingCalculates profit margin, handles divide by zerodivide calculation margin percentage
Calculated ColumnsBasicAge CalculationDATEDIFF(Customers[BirthDate], TODAY(), YEAR)Date difference in yearsCalculates customer age from birth datedatediff age date calculation
Calculated ColumnsBasicExtended AmountSales[Quantity] * Sales[UnitPrice]Simple multiplicationCalculates line item totalmultiply calculation product
Calculated ColumnsConditionalCustomer TierIF(Customers[TotalSpend] > 10000, “Premium”, IF(Customers[TotalSpend] > 5000, “Standard”, “Basic”))Nested IF logicCategorizes customers into tiersif nested conditional category
Calculated ColumnsConditionalSales CategorySWITCH(TRUE(), Sales[Amount] > 1000, “High”, Sales[Amount] > 500, “Medium”, “Low”)SWITCH with conditionsCategorizes sales by amount rangesswitch case conditional category
Calculated ColumnsConditionalIs PremiumIF(Products[Price] > 100, TRUE(), FALSE())Boolean flagCreates true/false flag for premium productsboolean flag if true false
Calculated ColumnsConditionalDiscount EligibleProducts[Category] = “Electronics” && Products[Stock] > 100AND conditionChecks multiple conditions for eligibilityand condition boolean logic
MeasuresBasicTotal Revenue MeasureSUM(Sales[Amount])Basic measure sumMeasure that sums revenue (not calculated column)measure sum total
MeasuresBasicTransaction CountCOUNTROWS(Sales)Count measureCounts number of transactionsmeasure count countrows
MeasuresBasicAverage Order ValueDIVIDE(SUM(Sales[Amount]), COUNTROWS(Sales))Calculated measureAverage revenue per transactionmeasure average aov calculation
MeasuresBasicDistinct Customer CountDISTINCTCOUNT(Sales[CustomerID])Unique count measureCounts unique customers in current contextmeasure distinctcount unique
MeasuresAdvancedSales RankRANKX(ALL(Products[ProductName]), [Total Revenue Measure])Ranking measureRanks products by revenuerankx rank measure
MeasuresAdvancedPercent of TotalDIVIDE([Total Revenue Measure], CALCULATE([Total Revenue Measure], ALL(Products)))Percentage of grand totalCalculates each item’s percentage of totalpercent percentage total all
MeasuresAdvancedRunning TotalCALCULATE([Total Revenue Measure], FILTER(ALLSELECTED(Calendar), Calendar[Date] <= MAX(Calendar[Date])))Cumulative sumRunning total up to current daterunning cumulative total
MeasuresAdvancedMoving AverageAVERAGEX(DATESINPERIOD(Calendar[Date], LASTDATE(Calendar[Date]), -3, MONTH), [Total Revenue Measure])3-month moving averageAverage of last 3 monthsmoving average rolling averagex
RelationshipsNavigationRelated ValueRELATED(Products[ProductName])Get value from one sideRetrieves value from related table (many to one)related lookup relationship
RelationshipsNavigationRelated Table SumSUMX(RELATEDTABLE(Sales), Sales[Amount])Aggregate from many sideSums values from related child recordsrelatedtable sumx relationship
RelationshipsNavigationRelated CountCOUNTROWS(RELATEDTABLE(Orders))Count related rowsCounts number of related ordersrelatedtable countrows relationship
RelationshipsInactiveUse Inactive RelationshipCALCULATE(SUM(Sales[Amount]), USERELATIONSHIP(Calendar[Date], Sales[ShipDate]))Activate inactive relationshipUses ship date instead of order date relationshipuserelationship inactive alternate
Table FunctionsManipulationReturn Filtered TableFILTER(Customers, Customers[TotalSpend] > 1000)Filter returns tableReturns table of high-spending customersfilter table return
Table FunctionsManipulationAdd Calculated ColumnADDCOLUMNS(Products, “PriceWithTax”, Products[Price] * 1.1)Add column to tableAdds calculated column to table expressionaddcolumns calculate extend
Table FunctionsManipulationSelect Specific ColumnsSELECTCOLUMNS(Customers, “Name”, Customers[FullName], “Amount”, Customers[TotalSpend])Choose columnsCreates table with selected columns onlyselectcolumns choose projection
Table FunctionsManipulationDistinct ValuesDISTINCT(Products[Category])Unique values tableReturns table of unique category valuesdistinct unique values
Table FunctionsManipulationGet Top NTOPN(10, Sales, Sales[Amount], DESC)Top recordsReturns top 10 sales by amounttopn top limit
Table FunctionsValuesValues in ColumnVALUES(Products[Category])Distinct with relationshipsReturns distinct values respecting relationshipsvalues distinct relationship
Table FunctionsValuesAll ValuesALL(Products[Category])All distinct valuesReturns all distinct values ignoring filtersall values distinct
StatisticalDistributionMedian SalesMEDIAN(Sales[Amount])Middle valueReturns median (50th percentile) of salesmedian middle percentile
StatisticalDistributionPercentile ValuePERCENTILE.INC(Sales[Amount], 0.90)90th percentileReturns value at 90th percentilepercentile distribution
StatisticalVarianceStandard DeviationSTDEV.P(Sales[Amount])Population std deviationCalculates standard deviation of salesstdev standard deviation variance
LogicalConditionsAND ConditionAND(Sales[Amount] > 100, Sales[Quantity] > 5)Multiple conditions must be trueReturns true only if all conditions are trueand logic boolean all
LogicalConditionsOR ConditionOR(Sales[Region] = “East”, Sales[Region] = “West”)Any condition can be trueReturns true if any condition is trueor logic boolean any
LogicalConditionsNOT ConditionNOT(Customers[Status] = “Inactive”)NegationReturns opposite boolean valuenot logic negate opposite
LogicalBlank HandlingIs Blank CheckIF(ISBLANK(Sales[ShipDate]), “Not Shipped”, “Shipped”)Check for blank valuesTests if value is blank/nullisblank null empty check
LogicalBlank HandlingCoalesce BlanksCOALESCE(Sales[Discount], 0)Replace blanksReturns first non-blank value or defaultcoalesce blank null default
TextManipulationUppercase TextUPPER(Customers[Name])Convert to uppercaseConverts text to all uppercaseupper uppercase case
TextManipulationLowercase TextLOWER(Products[Description])Convert to lowercaseConverts text to all lowercaselower lowercase case
TextManipulationExtract SubstringMID(Customers[AccountNumber], 4, 6)Extract middle portionExtracts 6 characters starting at position 4mid substring extract
TextManipulationText LengthLEN(Products[SKU])Character countReturns number of characterslen length count
TextManipulationTrim SpacesTRIM(Customers[Name])Remove extra spacesRemoves leading/trailing spacestrim space clean
TextSearchFind Text PositionFIND(“@”, Customers[Email])Search for substringReturns position of @ symbolfind search position
TextSearchContains TextCONTAINSSTRING(Products[Description], “premium”)Check if containsReturns true if text contains substringcontains search find
DateExtractionYear from DateYEAR(Sales[OrderDate])Extract yearReturns year portion of dateyear extract date
DateExtractionMonth from DateMONTH(Sales[OrderDate])Extract month numberReturns month number (1-12)month extract date
DateExtractionMonth NameFORMAT(Sales[OrderDate], “MMMM”)Format month nameReturns full month nameformat month name
DateExtractionDay of WeekWEEKDAY(Sales[OrderDate])Day number (1-7)Returns day of week as numberweekday day extract
DateExtractionQuarterQUARTER(Sales[OrderDate])Extract quarterReturns quarter number (1-4)quarter extract date
DateCalculationDays BetweenDATEDIFF(Sales[OrderDate], Sales[ShipDate], DAY)Date differenceCalculates days between two datesdatediff difference days
DateCalculationAdd DaysSales[OrderDate] + 30Date arithmeticAdds 30 days to order dateadd date arithmetic days
DateCurrentToday’s DateTODAY()Current dateReturns current date without timetoday current date
DateCurrentNow DateTimeNOW()Current date and timeReturns current date and timenow current datetime
InformationType CheckingIs NumberISNUMBER(Sales[Amount])Check numeric typeReturns true if value is numericisnumber type check
InformationType CheckingIs TextISTEXT(Products[SKU])Check text typeReturns true if value is textistext type check
InformationError HandlingIs ErrorISERROR(DIVIDE(Sales[Profit], Sales[Revenue]))Check for errorsReturns true if expression has erroriserror error check
InformationError HandlingIf ErrorIFERROR(DIVIDE(Sales[Profit], Sales[Revenue]), 0)Handle errors gracefullyReturns 0 if calculation errorsiferror error handle
VariablesPerformanceUsing VariablesVAR TotalSales = SUM(Sales[Amount]) VAR AvgSale = AVERAGE(Sales[Amount]) RETURN DIVIDE(TotalSales, AvgSale)Store intermediate resultsCalculates values once, reuses themvar variable performance reuse
VariablesReadabilityMultiple VariablesVAR CurrentSales = [Total Revenue Measure] VAR PriorSales = CALCULATE([Total Revenue Measure], SAMEPERIODLASTYEAR(Calendar[Date])) RETURN CurrentSales – PriorSalesComplex calculation clarityMakes complex DAX more readablevar variable readability
IteratorRow ContextSum with ExpressionSUMX(Sales, Sales[Quantity] * Sales[UnitPrice])Row-by-row calculationEvaluates expression for each row then sumssumx iterator row context
IteratorRow ContextAverage with ExpressionAVERAGEX(Sales, Sales[Quantity] * Sales[UnitPrice])Row-by-row averageCalculates expression per row then averagesaveragex iterator average
IteratorRow ContextCount with ConditionCOUNTX(FILTER(Sales, Sales[Amount] > 100), Sales[OrderID])Conditional countingCounts rows meeting criteriacountx iterator count filter
IteratorRow ContextMin with ExpressionMINX(Products, Products[Price] * 0.9)Minimum calculated valueFinds minimum of calculated valuesminx iterator minimum
IteratorRow ContextMax with ExpressionMAXX(Products, Products[Price] * 1.1)Maximum calculated valueFinds maximum of calculated valuesmaxx iterator maximum

Privacy Settings
We use cookies to enhance your experience while using our website. If you are using our Services via a browser you can restrict, block or remove cookies through your web browser settings. We also use content and scripts from third parties that may use tracking technologies. You can selectively provide your consent below to allow such third party embeds. For complete information about the cookies we use, data we collect and how we process them, please check our Privacy Policy
Youtube
Consent to display content from Youtube
Vimeo
Consent to display content from Vimeo
Google Maps
Consent to display content from Google