{"kind":"AgentDefinition","metadata":{"namespace":"community","name":"power-bi-dax-best-practices","version":"0.1.0"},"spec":{"agents_md":"---\ndescription: 'Comprehensive Power BI DAX best practices and patterns based on Microsoft guidance for creating efficient, maintainable, and performant DAX formulas.'\napplyTo: '**/*.{pbix,dax,md,txt}'\n---\n\n# Power BI DAX Best Practices\n\n## Overview\nThis document provides comprehensive instructions for writing efficient, maintainable, and performant DAX (Data Analysis Expressions) formulas in Power BI, based on Microsoft's official guidance and best practices.\n\n## Core DAX Principles\n\n### 1. Formula Structure and Variables\nAlways use variables to improve performance, readability, and debugging:\n\n```dax\n// ✅ PREFERRED: Using variables for clarity and performance\nSales YoY Growth % =\nVAR CurrentSales = [Total Sales]\nVAR PreviousYearSales = \n    CALCULATE(\n        [Total Sales],\n        SAMEPERIODLASTYEAR('Date'[Date])\n    )\nRETURN\n    DIVIDE(CurrentSales - PreviousYearSales, PreviousYearSales)\n\n// ❌ AVOID: Repeated calculations without variables  \nSales YoY Growth % =\nDIVIDE(\n    [Total Sales] - CALCULATE([Total Sales], SAMEPERIODLASTYEAR('Date'[Date])),\n    CALCULATE([Total Sales], SAMEPERIODLASTYEAR('Date'[Date]))\n)\n```\n\n**Key Benefits of Variables:**\n- **Performance**: Calculations are evaluated once and cached\n- **Readability**: Complex formulas become self-documenting\n- **Debugging**: Can temporarily return variable values for testing\n- **Maintainability**: Changes need to be made in only one place\n\n### 2. Proper Reference Syntax\nFollow Microsoft's recommended patterns for column and measure references:\n\n```dax\n// ✅ ALWAYS fully qualify column references\nCustomer Count = \nDISTINCTCOUNT(Sales[CustomerID])\n\nProfit Margin = \nDIVIDE(\n    SUM(Sales[Profit]),\n    SUM(Sales[Revenue])\n)\n\n// ✅ NEVER fully qualify measure references\nYTD Sales Growth = \nDIVIDE([YTD Sales] - [YTD Sales PY], [YTD Sales PY])\n\n// ❌ AVOID: Unqualified column references\nCustomer Count = DISTINCTCOUNT([CustomerID])  // Ambiguous\n\n// ❌ AVOID: Fully qualified measure references\nGrowth Rate = DIVIDE(Sales[Total Sales] - Sales[Total Sales PY], Sales[Total Sales PY])  // Breaks if measure moves\n```\n\n### 3. Error Handling Strategies\nImplement robust error handling using appropriate patterns:\n\n```dax\n// ✅ PREFERRED: Use DIVIDE function for safe division\nProfit Margin = \nDIVIDE([Total Profit], [Total Revenue])\n\n// ✅ PREFERRED: Use defensive strategies in model design\nAverage Order Value = \nVAR TotalOrders = COUNTROWS(Orders)\nVAR TotalRevenue = SUM(Orders[Amount])\nRETURN\n    IF(TotalOrders \u003e 0, DIVIDE(TotalRevenue, TotalOrders))\n\n// ❌ AVOID: ISERROR and IFERROR functions (performance impact)\nProfit Margin = \nIFERROR([Total Profit] / [Total Revenue], BLANK())\n\n// ❌ AVOID: Complex error handling that could be prevented\nUnsafe Calculation = \nIF(\n    OR(\n        ISBLANK([Revenue]),\n        [Revenue] = 0\n    ),\n    BLANK(),\n    [Profit] / [Revenue]\n)\n```\n\n## DAX Function Categories and Best Practices\n\n### Aggregation Functions\n```dax\n// Use appropriate aggregation functions for performance\nCustomer Count = DISTINCTCOUNT(Sales[CustomerID])  // ✅ For unique counts\nOrder Count = COUNTROWS(Orders)                    // ✅ For row counts  \nAverage Deal Size = AVERAGE(Sales[DealValue])      // ✅ For averages\n\n// Avoid COUNT when COUNTROWS is more appropriate\n// ❌ COUNT(Sales[OrderID]) - slower for counting rows\n// ✅ COUNTROWS(Sales) - faster and more explicit\n```\n\n### Filter and Context Functions\n```dax\n// Efficient use of CALCULATE with multiple filters\nHigh Value Customers = \nCALCULATE(\n    DISTINCTCOUNT(Sales[CustomerID]),\n    Sales[OrderValue] \u003e 1000,\n    Sales[OrderDate] \u003e= DATE(2024,1,1)\n)\n\n// Proper context modification patterns\nSame Period Last Year = \nCALCULATE(\n    [Total Sales],\n    SAMEPERIODLASTYEAR('Date'[Date])\n)\n\n// Using FILTER appropriately (avoid as filter argument)\n// ✅ PREFERRED: Direct filter expression\nHigh Value Orders = \nCALCULATE(\n    [Total Sales],\n    Sales[OrderValue] \u003e 1000\n)\n\n// ❌ AVOID: FILTER as filter argument (unless table manipulation needed)\nHigh Value Orders = \nCALCULATE(\n    [Total Sales],\n    FILTER(Sales, Sales[OrderValue] \u003e 1000)\n)\n```\n\n### Time Intelligence Patterns\n```dax\n// Standard time intelligence measures\nYTD Sales = \nCALCULATE(\n    [Total Sales],\n    DATESYTD('Date'[Date])\n)\n\nMTD Sales = \nCALCULATE(\n    [Total Sales],\n    DATESMTD('Date'[Date])\n)\n\n// Moving averages with proper date handling\n3-Month Moving Average = \nVAR CurrentDate = MAX('Date'[Date])\nVAR StartDate = EDATE(CurrentDate, -2)\nRETURN\n    CALCULATE(\n        DIVIDE([Total Sales], 3),\n        DATESBETWEEN(\n            'Date'[Date],\n            StartDate,\n            CurrentDate\n        )\n    )\n\n// Quarter over quarter growth\nQoQ Growth = \nVAR CurrentQuarter = [Total Sales]\nVAR PreviousQuarter = \n    CALCULATE(\n        [Total Sales],\n        DATEADD('Date'[Date], -1, QUARTER)\n    )\nRETURN\n    DIVIDE(CurrentQuarter - PreviousQuarter, PreviousQuarter)\n```\n\n### Advanced DAX Patterns\n```dax\n// Ranking with proper context\nProduct Rank = \nRANKX(\n    ALL(Product[ProductName]),\n    [Total Sales],\n    ,\n    DESC,\n    DENSE\n)\n\n// Running totals\nRunning Total = \nCALCULATE(\n    [Total Sales],\n    FILTER(\n        ALL('Date'[Date]),\n        'Date'[Date] \u003c= MAX('Date'[Date])\n    )\n)\n\n// ABC Analysis (Pareto)\nABC Classification = \nVAR CurrentProductSales = [Total Sales]\nVAR TotalSales = CALCULATE([Total Sales], ALL(Product))\nVAR RunningTotal = \n    CALCULATE(\n        [Total Sales],\n        FILTER(\n            ALL(Product),\n            [Total Sales] \u003e= CurrentProductSales\n        )\n    )\nVAR PercentageOfTotal = DIVIDE(RunningTotal, TotalSales)\nRETURN\n    SWITCH(\n        TRUE(),\n        PercentageOfTotal \u003c= 0.8, \"A\",\n        PercentageOfTotal \u003c= 0.95, \"B\",\n        \"C\"\n    )\n```\n\n## Performance Optimization Techniques\n\n### 1. Efficient Variable Usage\n```dax\n// ✅ Store expensive calculations in variables\nComplex Measure = \nVAR BaseCalculation = \n    CALCULATE(\n        SUM(Sales[Amount]),\n        FILTER(\n            Product,\n            Product[Category] = \"Electronics\"\n        )\n    )\nVAR PreviousYear = \n    CALCULATE(\n        BaseCalculation,\n        SAMEPERIODLASTYEAR('Date'[Date])\n    )\nRETURN\n    DIVIDE(BaseCalculation - PreviousYear, PreviousYear)\n```\n\n### 2. Context Transition Optimization\n```dax\n// ✅ Minimize context transitions in iterator functions\nTotal Product Profit = \nSUMX(\n    Product,\n    Product[UnitPrice] - Product[UnitCost]\n)\n\n// ❌ Avoid unnecessary calculated columns in large tables\n// Create in Power Query instead when possible\n```\n\n### 3. Efficient Filtering Patterns\n```dax\n// ✅ Use table expressions efficiently\nTop 10 Customers = \nCALCULATE(\n    [Total Sales],\n    TOPN(\n        10,\n        ALL(Customer[CustomerName]),\n        [Total Sales]\n    )\n)\n\n// ✅ Leverage relationship filtering\nSales with Valid Customers = \nCALCULATE(\n    [Total Sales],\n    FILTER(\n        Customer,\n        NOT(ISBLANK(Customer[CustomerName]))\n    )\n)\n```\n\n## Common DAX Anti-Patterns to Avoid\n\n### 1. Performance Anti-Patterns\n```dax\n// ❌ AVOID: Nested CALCULATE functions\nInefficient Nested = \nCALCULATE(\n    CALCULATE(\n        [Total Sales],\n        Product[Category] = \"Electronics\"\n    ),\n    'Date'[Year] = 2024\n)\n\n// ✅ PREFERRED: Single CALCULATE with multiple filters\nEfficient Single = \nCALCULATE(\n    [Total Sales],\n    Product[Category] = \"Electronics\",\n    'Date'[Year] = 2024\n)\n\n// ❌ AVOID: Converting BLANK to zero unnecessarily\nSales with Zero = \nIF(ISBLANK([Total Sales]), 0, [Total Sales])\n\n// ✅ PREFERRED: Keep BLANK as BLANK for better visual behavior\nSales = SUM(Sales[Amount])\n```\n\n### 2. Readability Anti-Patterns\n```dax\n// ❌ AVOID: Complex nested expressions without variables\nComplex Without Variables = \nDIVIDE(\n    CALCULATE(SUM(Sales[Revenue]), Sales[Date] \u003e= DATE(2024,1,1)) - \n    CALCULATE(SUM(Sales[Revenue]), Sales[Date] \u003e= DATE(2023,1,1), Sales[Date] \u003c DATE(2024,1,1)),\n    CALCULATE(SUM(Sales[Revenue]), Sales[Date] \u003e= DATE(2023,1,1), Sales[Date] \u003c DATE(2024,1,1))\n)\n\n// ✅ PREFERRED: Clear variable-based structure\nYear Over Year Growth = \nVAR CurrentYear = \n    CALCULATE(\n        SUM(Sales[Revenue]),\n        Sales[Date] \u003e= DATE(2024,1,1)\n    )\nVAR PreviousYear = \n    CALCULATE(\n        SUM(Sales[Revenue]),\n        Sales[Date] \u003e= DATE(2023,1,1),\n        Sales[Date] \u003c DATE(2024,1,1)\n    )\nRETURN\n    DIVIDE(CurrentYear - PreviousYear, PreviousYear)\n```\n\n## DAX Debugging and Testing Strategies\n\n### 1. Variable-Based Debugging\n```dax\n// Use this pattern for step-by-step debugging\nDebug Measure = \nVAR Step1 = CALCULATE([Sales], 'Date'[Year] = 2024)\nVAR Step2 = CALCULATE([Sales], 'Date'[Year] = 2023)  \nVAR Step3 = Step1 - Step2\nVAR Step4 = DIVIDE(Step3, Step2)\nRETURN\n    -- Return different variables for testing:\n    -- Step1  -- Test current year sales\n    -- Step2  -- Test previous year sales  \n    -- Step3  -- Test difference calculation\n    Step4     -- Final result\n```\n\n### 2. Testing Patterns\n```dax\n// Include data validation in measures\nValidated Measure = \nVAR Result = [Complex Calculation]\nVAR IsValid = \n    Result \u003e= 0 \u0026\u0026 \n    Result \u003c= 1 \u0026\u0026 \n    NOT(ISBLANK(Result))\nRETURN\n    IF(IsValid, Result, BLANK())\n```\n\n## Measure Organization and Naming\n\n### 1. Naming Conventions\n```dax\n// Use descriptive, consistent naming\nTotal Sales = SUM(Sales[Amount])\nTotal Sales YTD = CALCULATE([Total Sales], DATESYTD('Date'[Date]))\nTotal Sales PY = CALCULATE([Total Sales], SAMEPERIODLASTYEAR('Date'[Date]))\nSales Growth % = DIVIDE([Total Sales] - [Total Sales PY], [Total Sales PY])\n\n// Prefix for measure categories\nKPI - Revenue Growth = [Sales Growth %]\nCalc - Days Since Last Order = DATEDIFF(MAX(Orders[OrderDate]), TODAY(), DAY)\nBase - Order Count = COUNTROWS(Orders)\n```\n\n### 2. Measure Dependencies\n```dax\n// Build measures hierarchically for reusability\n// Base measures\nRevenue = SUM(Sales[Revenue])\nCost = SUM(Sales[Cost])\n\n// Derived measures  \nProfit = [Revenue] - [Cost]\nMargin % = DIVIDE([Profit], [Revenue])\n\n// Advanced measures\nProfit YTD = CALCULATE([Profit], DATESYTD('Date'[Date]))\nMargin Trend = [Margin %] - CALCULATE([Margin %], PREVIOUSMONTH('Date'[Date]))\n```\n\n## Model Integration Best Practices\n\n### 1. Working with Star Schema\n```dax\n// Leverage proper relationships\nSales by Category = \nCALCULATE(\n    [Total Sales],\n    Product[Category] = \"Electronics\"\n)\n\n// Use dimension tables for filtering\nRegional Sales = \nCALCULATE(\n    [Total Sales],\n    Geography[Region] = \"North America\"\n)\n```\n\n### 2. Handle Missing Relationships\n```dax\n// When direct relationships don't exist\nCross Table Analysis = \nVAR CustomerList = VALUES(Customer[CustomerID])\nRETURN\n    CALCULATE(\n        [Total Sales],\n        FILTER(\n            Sales,\n            Sales[CustomerID] IN CustomerList\n        )\n    )\n```\n\n## Advanced DAX Concepts\n\n### 1. Row Context vs Filter Context\n```dax\n// Understanding context differences\nRow Context Example = \nSUMX(\n    Sales,\n    Sales[Quantity] * Sales[UnitPrice]  // Row context\n)\n\nFilter Context Example = \nCALCULATE(\n    [Total Sales],  // Filter context\n    Product[Category] = \"Electronics\"\n)\n```\n\n### 2. Context Transition\n```dax\n// When row context becomes filter context\nSales Per Product = \nSUMX(\n    Product,\n    CALCULATE([Total Sales])  // Context transition happens here\n)\n```\n\n### 3. Extended Columns and Computed Tables\n```dax\n// Use for complex analytical scenarios\nProduct Analysis = \nADDCOLUMNS(\n    Product,\n    \"Total Sales\", CALCULATE([Total Sales]),\n    \"Rank\", RANKX(ALL(Product), CALCULATE([Total Sales])),\n    \"Category Share\", DIVIDE(\n        CALCULATE([Total Sales]),\n        CALCULATE([Total Sales], ALL(Product[ProductName]))\n    )\n)\n```\n\n### 4. Advanced Time Intelligence Patterns\n```dax\n// Multi-period comparisons with calculation groups\n// Example showing how to create dynamic time calculations\nDynamic Period Comparison = \nVAR CurrentPeriodValue = \n    CALCULATE(\n        [Sales],\n        'Time Intelligence'[Time Calculation] = \"Current\"\n    )\nVAR PreviousPeriodValue = \n    CALCULATE(\n        [Sales],\n        'Time Intelligence'[Time Calculation] = \"PY\"\n    )\nVAR MTDCurrent = \n    CALCULATE(\n        [Sales],\n        'Time Intelligence'[Time Calculation] = \"MTD\"\n    )\nVAR MTDPrevious = \n    CALCULATE(\n        [Sales],\n        'Time Intelligence'[Time Calculation] = \"PY MTD\"\n    )\nRETURN\n    DIVIDE(MTDCurrent - MTDPrevious, MTDPrevious)\n\n// Working with fiscal years and custom calendars\nFiscal YTD Sales = \nVAR FiscalYearStart = \n    DATE(\n        IF(MONTH(MAX('Date'[Date])) \u003e= 7, YEAR(MAX('Date'[Date])), YEAR(MAX('Date'[Date])) - 1),\n        7,\n        1\n    )\nVAR FiscalYearEnd = MAX('Date'[Date])\nRETURN\n    CALCULATE(\n        [Total Sales],\n        DATESBETWEEN(\n            'Date'[Date],\n            FiscalYearStart,\n            FiscalYearEnd\n        )\n    )\n```\n\n### 5. Advanced Performance Optimization Techniques\n```dax\n// Optimized running totals\nRunning Total Optimized = \nVAR CurrentDate = MAX('Date'[Date])\nRETURN\n    CALCULATE(\n        [Total Sales],\n        FILTER(\n            ALL('Date'[Date]),\n            'Date'[Date] \u003c= CurrentDate\n        )\n    )\n\n// Efficient ABC Analysis using RANKX\nABC Classification Advanced = \nVAR ProductRank = \n    RANKX(\n        ALL(Product[ProductName]),\n        [Total Sales],\n        ,\n        DESC,\n        DENSE\n    )\nVAR TotalProducts = COUNTROWS(ALL(Product[ProductName]))\nVAR ClassAThreshold = TotalProducts * 0.2\nVAR ClassBThreshold = TotalProducts * 0.5\nRETURN\n    SWITCH(\n        TRUE(),\n        ProductRank \u003c= ClassAThreshold, \"A\",\n        ProductRank \u003c= ClassBThreshold, \"B\",\n        \"C\"\n    )\n\n// Efficient Top N with ties handling\nTop N Products with Ties = \nVAR TopNValue = 10\nVAR MinTopNSales = \n    CALCULATE(\n        MIN([Total Sales]),\n        TOPN(\n            TopNValue,\n            ALL(Product[ProductName]),\n            [Total Sales]\n        )\n    )\nRETURN\n    IF(\n        [Total Sales] \u003e= MinTopNSales,\n        [Total Sales],\n        BLANK()\n    )\n```\n\n### 6. Complex Analytical Scenarios\n```dax\n// Customer cohort analysis\nCohort Retention Rate = \nVAR CohortMonth = \n    CALCULATE(\n        MIN('Date'[Date]),\n        ALLEXCEPT(Sales, Sales[CustomerID])\n    )\nVAR CurrentMonth = MAX('Date'[Date])\nVAR MonthsFromCohort = \n    DATEDIFF(CohortMonth, CurrentMonth, MONTH)\nVAR CohortCustomers = \n    CALCULATE(\n        DISTINCTCOUNT(Sales[CustomerID]),\n        'Date'[Date] = CohortMonth\n    )\nVAR ActiveCustomersInMonth = \n    CALCULATE(\n        DISTINCTCOUNT(Sales[CustomerID]),\n        'Date'[Date] = CurrentMonth,\n        FILTER(\n            Sales,\n            CALCULATE(\n                MIN('Date'[Date]),\n                ALLEXCEPT(Sales, Sales[CustomerID])\n            ) = CohortMonth\n        )\n    )\nRETURN\n    DIVIDE(ActiveCustomersInMonth, CohortCustomers)\n\n// Market basket analysis\nProduct Affinity Score = \nVAR CurrentProduct = SELECTEDVALUE(Product[ProductName])\nVAR RelatedProduct = SELECTEDVALUE('Related Product'[ProductName])\nVAR TransactionsWithBoth = \n    CALCULATE(\n        DISTINCTCOUNT(Sales[TransactionID]),\n        Sales[ProductName] = CurrentProduct\n    ) +\n    CALCULATE(\n        DISTINCTCOUNT(Sales[TransactionID]),\n        Sales[ProductName] = RelatedProduct\n    ) -\n    CALCULATE(\n        DISTINCTCOUNT(Sales[TransactionID]),\n        Sales[ProductName] = CurrentProduct,\n        CALCULATE(\n            COUNTROWS(Sales),\n            Sales[ProductName] = RelatedProduct,\n            Sales[TransactionID] = EARLIER(Sales[TransactionID])\n        ) \u003e 0\n    )\nVAR TotalTransactions = DISTINCTCOUNT(Sales[TransactionID])\nRETURN\n    DIVIDE(TransactionsWithBoth, TotalTransactions)\n```\n\n### 7. Advanced Debugging and Profiling\n```dax\n// Debug measure with detailed variable inspection\nComplex Measure Debug = \nVAR Step1_FilteredSales = \n    CALCULATE(\n        [Sales],\n        Product[Category] = \"Electronics\",\n        'Date'[Year] = 2024\n    )\nVAR Step2_PreviousYear = \n    CALCULATE(\n        [Sales],\n        Product[Category] = \"Electronics\",\n        'Date'[Year] = 2023\n    )\nVAR Step3_GrowthAbsolute = Step1_FilteredSales - Step2_PreviousYear\nVAR Step4_GrowthPercentage = DIVIDE(Step3_GrowthAbsolute, Step2_PreviousYear)\nVAR DebugInfo = \n    \"Current: \" \u0026 FORMAT(Step1_FilteredSales, \"#,0\") \u0026 \n    \" | Previous: \" \u0026 FORMAT(Step2_PreviousYear, \"#,0\") \u0026\n    \" | Growth: \" \u0026 FORMAT(Step4_GrowthPercentage, \"0.00%\")\nRETURN\n    -- Switch between these for debugging:\n    -- Step1_FilteredSales    -- Test current year\n    -- Step2_PreviousYear     -- Test previous year\n    -- Step3_GrowthAbsolute   -- Test absolute growth\n    -- DebugInfo              -- Show debug information\n    Step4_GrowthPercentage    -- Final result\n\n// Performance monitoring measure\nQuery Performance Monitor = \nVAR StartTime = NOW()\nVAR Result = [Complex Calculation]\nVAR EndTime = NOW()\nVAR ExecutionTime = DATEDIFF(StartTime, EndTime, SECOND)\nVAR WarningThreshold = 5 // seconds\nRETURN\n    IF(\n        ExecutionTime \u003e WarningThreshold,\n        \"⚠️ Slow: \" \u0026 ExecutionTime \u0026 \"s - \" \u0026 Result,\n        Result\n    )\n```\n\n### 8. Working with Complex Data Types\n```dax\n// JSON parsing and manipulation\nExtract JSON Value = \nVAR JSONString = SELECTEDVALUE(Data[JSONColumn])\nVAR ParsedValue = \n    IF(\n        NOT(ISBLANK(JSONString)),\n        PATHCONTAINS(JSONString, \"$.analytics.revenue\"),\n        BLANK()\n    )\nRETURN\n    ParsedValue\n\n// Dynamic measure selection\nDynamic Measure Selector = \nVAR SelectedMeasure = SELECTEDVALUE('Measure Selector'[MeasureName])\nRETURN\n    SWITCH(\n        SelectedMeasure,\n        \"Revenue\", [Total Revenue],\n        \"Profit\", [Total Profit],\n        \"Units\", [Total Units],\n        \"Margin\", [Profit Margin %],\n        BLANK()\n    )\n```\n\n## DAX Formula Documentation\n\n### 1. Commenting Best Practices\n```dax\n/* \nBusiness Rule: Calculate customer lifetime value based on:\n- Average order value over customer lifetime\n- Purchase frequency (orders per year)  \n- Customer lifespan (years since first order)\n- Retention probability based on last order date\n*/\nCustomer Lifetime Value = \nVAR AvgOrderValue = \n    DIVIDE(\n        CALCULATE(SUM(Sales[Amount])),\n        CALCULATE(DISTINCTCOUNT(Sales[OrderID]))\n    )\nVAR OrdersPerYear = \n    DIVIDE(\n        CALCULATE(DISTINCTCOUNT(Sales[OrderID])),\n        DATEDIFF(\n            CALCULATE(MIN(Sales[OrderDate])),\n            CALCULATE(MAX(Sales[OrderDate])),\n            YEAR\n        ) + 1  -- Add 1 to avoid division by zero for customers with orders in single year\n    )\nVAR CustomerLifespanYears = 3  -- Business assumption: average 3-year relationship\nRETURN\n    AvgOrderValue * OrdersPerYear * CustomerLifespanYears\n```\n\n### 2. Version Control and Change Management\n```dax\n// Include version history in measure descriptions\n/*\nVersion History:\nv1.0 - Initial implementation (2024-01-15)\nv1.1 - Added null checking for edge cases (2024-02-01)  \nv1.2 - Optimized performance using variables (2024-02-15)\nv2.0 - Changed business logic per stakeholder feedback (2024-03-01)\n\nBusiness Logic:\n- Excludes returns and cancelled orders\n- Uses ship date for revenue recognition\n- Applies regional tax calculations\n*/\n```\n\n## Testing and Validation Framework\n\n### 1. Unit Testing Patterns\n```dax\n// Create test measures for validation\nTest - Sales Sum = \nVAR DirectSum = SUM(Sales[Amount])\nVAR MeasureResult = [Total Sales]\nVAR Difference = ABS(DirectSum - MeasureResult)\nRETURN\n    IF(Difference \u003c 0.01, \"PASS\", \"FAIL: \" \u0026 Difference)\n```\n\n### 2. Performance Testing\n```dax\n// Monitor execution time for complex measures\nPerformance Monitor = \nVAR StartTime = NOW()\nVAR Result = [Complex Calculation]\nVAR EndTime = NOW()\nVAR Duration = DATEDIFF(StartTime, EndTime, SECOND)\nRETURN\n    \"Result: \" \u0026 Result \u0026 \" | Duration: \" \u0026 Duration \u0026 \"s\"\n```\n\nRemember: Always validate DAX formulas with business users to ensure calculations match business requirements and expectations. Use Power BI's Performance Analyzer and DAX Studio for performance optimization and debugging.","description":"Comprehensive Power BI DAX best practices and patterns based on Microsoft guidance for creating efficient, maintainable, and performant DAX formulas.","import":{"commit_sha":"541b7819d8c3545c6df122491af4fa1eae415779","imported_at":"2026-05-18T20:05:35Z","license_text":"MIT License\n\nCopyright GitHub, Inc.\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.","owner":"github","repo":"github/awesome-copilot","source_url":"https://github.com/github/awesome-copilot/blob/541b7819d8c3545c6df122491af4fa1eae415779/instructions/power-bi-dax-best-practices.instructions.md"},"manifest":{}},"content_hash":[178,107,37,191,19,227,150,120,229,222,109,170,225,29,153,168,176,213,92,22,123,158,174,248,92,242,166,176,226,132,48,171],"trust_level":"unsigned","yanked":false}
