@microsoft/rayfin-semantic-model-pack 0.0.0-stage → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,862 @@
1
+ # DAX Core Reference
2
+
3
+ Shared DAX knowledge used across queries, measures, and calculated columns.
4
+
5
+ ## DAX Syntax Rules
6
+
7
+ - Measures are named objects in the semantic model. Although numeric measures are the most common, they can return values of any data type. Measures specify how to aggregate data. **Measures should be used first** to answer user requests in a DAX query before a new DAX formula is used to aggregate data in the DAX query.
8
+ - **EVALUATE Statement**: This is not a function but a statement. It must always precede a table expression. Avoid pairing EVALUATE with scalar functions like CONCATENATEX, SUMX, DISTINCTCOUNT, etc.
9
+ - Use the fully-qualified name, such as `'Table'[Column]`, for column references, and the simple name, like `[Measure]`, for measure references.
10
+ - CALCULATE takes a scalar expression as its first argument and returns a scalar value. CALCULATETABLE takes a table expression as its first argument and returns a table.
11
+ - The SUMMARIZECOLUMNS Function: This function requires a specific order of input parameters. Begin with the 'groupby' columns, then add filters, and end with aggregations or measures.
12
+ - Do not use SUMMARIZECOLUMNS when there is no aggregation or measure and the 'groupby' columns belong to more than one table; use VALUES, SUMMARIZE, or SELECTCOLUMNS instead.
13
+ - When using table expressions like SELECTCOLUMNS or CALCULATETABLE, include any columns that will be needed after, for example in an ORDER BY, FILTER.
14
+ - Filters applied to one table can propagate to another table across a relationship based on the defined filter propagation which can be either unidirectional or bidirectional.
15
+ - Avoid using SQL keywords like SELECT, WHERE, HAVING, etc. within DAX expressions.
16
+ - When using the set functions INTERSECT, UNION, or EXCEPT, make sure both input tables produce an identical number of columns.
17
+ - When using DEFINE, only use single DEFINE and any VAR or MEASURE defined are separated by new line without commas.
18
+ - For any requests involving calculations or filters based on the current date or time, use the TODAY or NOW() functions.
19
+
20
+ ## CALCULATE & CALCULATETABLE
21
+
22
+ CALCULATE is the most important and powerful function in DAX. It evaluates a scalar expression in a modified filter context. CALCULATETABLE applies the same filter-context rules but returns a table expression instead of a scalar.
23
+
24
+ ### Syntax
25
+
26
+ ```dax
27
+ CALCULATE(<Expression> [, <Filter1> [, <Filter2> [, ...]]])
28
+ CALCULATETABLE(<TableExpression> [, <Filter1> [, <Filter2> [, ...]]])
29
+ ```
30
+
31
+ ### Parameters
32
+
33
+ | Parameter | Required | Description |
34
+ |-----------|----------|-------------|
35
+ | Expression | Yes | The scalar expression to evaluate (CALCULATE only) |
36
+ | TableExpression | Yes | The table expression to evaluate (CALCULATETABLE only) |
37
+ | Filter | No | Boolean condition, table expression, or CALCULATE/CALCULATETABLE modifier |
38
+
39
+ ### Return Value
40
+
41
+ - **CALCULATE**: Scalar value - the result of the expression evaluated in the modified filter context.
42
+ - **CALCULATETABLE**: Table value - the result of the table expression evaluated in the modified filter context.
43
+
44
+ ### Filter Argument Types
45
+
46
+ #### 1. Boolean Conditions (Compact Syntax)
47
+
48
+ ```dax
49
+ // Single column filter
50
+ CALCULATE([Sales Amount], 'Product'[Color] = "Red")
51
+
52
+ // IN operator for multiple values
53
+ CALCULATE([Sales Amount], 'Product'[Color] IN {"Red", "Blue"})
54
+ ```
55
+
56
+ #### 2. Table Expressions
57
+
58
+ ```dax
59
+ // Explicit table filter (equivalent to boolean)
60
+ CALCULATE(
61
+ [Sales Amount],
62
+ FILTER(ALL('Product'[Color]), 'Product'[Color] = "Red")
63
+ )
64
+ ```
65
+
66
+ #### 3. CALCULATE/CALCULATETABLE Modifiers
67
+
68
+ | Modifier | Purpose |
69
+ |----------|---------|
70
+ | `ALL()` | Remove filters from table or columns |
71
+ | `ALLCROSSFILTERED()` | Clear filters on the table and filters reaching it via cross-filtering |
72
+ | `ALLEXCEPT()` | Remove all filters except specified columns |
73
+ | `ALLSELECTED()` | Remove visual filters, keep slicers |
74
+ | `KEEPFILTERS()` | Intersect with existing filters |
75
+ | `REMOVEFILTERS()` | Remove filters (alias for ALL) |
76
+ | `USERELATIONSHIP()` | Activate an inactive relationship |
77
+ | `CROSSFILTER()` | Modify filter direction |
78
+
79
+ ### Context Transition
80
+
81
+ When CALCULATE or CALCULATETABLE is executed in a row context, it converts the row context to an equivalent filter context.
82
+
83
+ ```dax
84
+ // Inside an iterator, CALCULATE triggers context transition
85
+ Yearly Avg = AVERAGEX(
86
+ VALUES('Date'[Calendar Year]),
87
+ CALCULATE(SUM(Sales[Amount])) // Row context becomes filter context
88
+ )
89
+ ```
90
+
91
+ Every measure reference implicitly wraps in CALCULATE, triggering context transition:
92
+
93
+ ```dax
94
+ // These are equivalent inside an iterator:
95
+ AVERAGEX(VALUES('Date'[Year]), CALCULATE([Sales Amount])) // Explicit CALCULATE is unnecessary
96
+ AVERAGEX(VALUES('Date'[Year]), [Sales Amount]) // Implicit CALCULATE
97
+ ```
98
+
99
+ ### Common Patterns
100
+
101
+ #### Percentage of Total
102
+
103
+ ```dax
104
+ % of Total = DIVIDE(
105
+ [Sales Amount],
106
+ CALCULATE([Sales Amount], ALL('Product'))
107
+ )
108
+ ```
109
+
110
+ #### Conditional Aggregation
111
+
112
+ ```dax
113
+ High Value Sales = CALCULATE(
114
+ [Sales Amount],
115
+ Sales[Amount] > 1000
116
+ )
117
+ ```
118
+
119
+ #### Time Intelligence
120
+
121
+ ```dax
122
+ Sales YTD = CALCULATE([Sales Amount], DATESYTD('Date'[Date]))
123
+ Sales PY = CALCULATE([Sales Amount], SAMEPERIODLASTYEAR('Date'[Date]))
124
+ ```
125
+
126
+ #### Multiple Filters (AND logic)
127
+
128
+ ```dax
129
+ Red Electronics = CALCULATE(
130
+ [Sales Amount],
131
+ 'Product'[Color] = "Red",
132
+ 'Product'[Category] = "Electronics"
133
+ )
134
+ ```
135
+
136
+ #### KEEPFILTERS - Intersect Filters
137
+
138
+ ```dax
139
+ // Without KEEPFILTERS: overrides existing Color filter (always Red+Blue)
140
+ Red Blue Sales = CALCULATE(
141
+ [Sales Amount],
142
+ 'Product'[Color] IN {"Red", "Blue"}
143
+ )
144
+
145
+ // With KEEPFILTERS: intersects with existing Color filter
146
+ Red Blue Keepfilters = CALCULATE(
147
+ [Sales Amount],
148
+ KEEPFILTERS('Product'[Color] IN {"Red", "Blue"})
149
+ )
150
+ ```
151
+
152
+ #### Using Relationship Modifiers
153
+
154
+ ```dax
155
+ Delivered Sales = CALCULATE(
156
+ [Sales Amount],
157
+ USERELATIONSHIP(Sales[Delivery Date], 'Date'[Date])
158
+ )
159
+ ```
160
+
161
+ ### Boolean Filter Restrictions
162
+
163
+ #### Cannot Reference Multiple Tables
164
+
165
+ ```dax
166
+ // Wrong - references both Product and Customer
167
+ CALCULATE([Sales], 'Product'[Color] = "Red" && 'Customer'[Region] = "West")
168
+
169
+ // Correct - each filter is a separate argument
170
+ CALCULATE(
171
+ [Sales],
172
+ 'Product'[Color] = "Red",
173
+ 'Customer'[Region] = "West"
174
+ )
175
+ ```
176
+
177
+ #### Cannot Use Measures Directly
178
+
179
+ ```dax
180
+ // Wrong - measure in boolean filter
181
+ CALCULATE([Sales], 'Product'[Price] > [Avg Price])
182
+
183
+ // Correct - use variable
184
+ VAR AvgPrice = [Avg Price]
185
+ RETURN CALCULATE([Sales], 'Product'[Price] > AvgPrice)
186
+ ```
187
+
188
+ #### Cannot Use Certain Table Functions in Boolean Filters
189
+
190
+ Some table functions are forbidden inside Boolean filter expressions. These functions can be passed directly as CALCULATE filter arguments, but cannot appear inside Boolean expressions (e.g., as the second operand of the `IN` operator).
191
+
192
+ Forbidden: `ADDCOLUMNS`, `FILTER`, `GROUPBY`, `SUMMARIZE`, `SUMMARIZECOLUMNS`, `TOPN`, `DATESBETWEEN`, `DATESINPERIOD`, `WINDOW`, `OFFSET`, `INDEX`, `RANK`, `INTERSECT`, `UNION`, `EXCEPT`, etc.
193
+
194
+ ```dax
195
+ // Wrong - FILTER inside IN operator
196
+ CALCULATE([Sales], 'Product'[Color] IN FILTER(ALL('Product'[Color]), LEFT('Product'[Color], 1) = "B"))
197
+
198
+ // Correct - use a simple Boolean predicate
199
+ CALCULATE([Sales], LEFT('Product'[Color], 1) = "B")
200
+
201
+ // Correct - use TREATAS instead of IN
202
+ CALCULATE(
203
+ [Reseller Sales],
204
+ TREATAS(
205
+ INTERSECT(
206
+ CALCULATETABLE(VALUES('InternetSales'[ProductKey]), 'Customer'[Age] > 60),
207
+ CALCULATETABLE(VALUES('InternetSales'[ProductKey]), 'Customer'[Age] < 16)
208
+ ),
209
+ 'ResellerSales'[ProductKey]
210
+ )
211
+ )
212
+
213
+ // Correct - evaluate table function in a variable first
214
+ VAR Threshold = AVERAGEX(TOPN(20, 'Product', [Sales], DESC), 'Product'[ListPrice])
215
+ RETURN CALCULATE([Sales], 'Product'[ListPrice] > Threshold)
216
+ ```
217
+
218
+ ### Quick Reference
219
+
220
+ | Pattern | Formula |
221
+ |---------|---------|
222
+ | Simple filter | `CALCULATE([M], Table[Col] = "Value")` |
223
+ | Multiple values | `CALCULATE([M], Table[Col] IN {"A", "B"})` |
224
+ | Remove filter | `CALCULATE([M], ALL(Table[Col]))` |
225
+ | Remove table filter | `CALCULATE([M], ALL(Table))` |
226
+ | Percentage of total | `DIVIDE([M], CALCULATE([M], ALL(Table)))` |
227
+ | Keep + new filter | `CALCULATE([M], KEEPFILTERS(Table[Col] = "X"))` |
228
+ | Time intelligence | `CALCULATE([M], DATESYTD('Date'[Date]))` |
229
+ | Different relationship | `CALCULATE([M], USERELATIONSHIP(...))` |
230
+ | Filtered table | `CALCULATETABLE(Table, Table[Col] = "Value")` |
231
+
232
+ ## SUMMARIZECOLUMNS
233
+
234
+ SUMMARIZECOLUMNS is the modern, high-performance function for grouping data and calculating aggregations in DAX queries. It's the preferred choice over SUMMARIZE when working with measures.
235
+
236
+ ### Syntax
237
+
238
+ ```dax
239
+ SUMMARIZECOLUMNS(
240
+ <groupBy_columnName> [, <groupBy_columnName>]...,
241
+ [<filterTable>]...,
242
+ [<name>, <expression>]...
243
+ )
244
+ ```
245
+
246
+ ### Parameters
247
+
248
+ - **groupBy_columnName** (optional): Column references to group by. Must be fully qualified (`Table[Column]`)
249
+ - **filterTable** (optional): Table expressions used to filter the result
250
+ - **name** (optional): Name for a calculated column
251
+ - **expression** (optional): DAX expression for a calculated column
252
+
253
+ **Critical:**
254
+ - **All parameter types are optional** - you can omit groupBy columns, filters, or aggregations as needed
255
+ - When present, parameters must follow this order: GroupBy Columns -> Filter Tables -> Aggregations/Measures
256
+ - Valid combinations include: filters + measures only (no groupBy), groupBy + measures only (no filters), etc.
257
+
258
+ ### Key Characteristics
259
+
260
+ #### 1. Automatic Blank Measure Row Elimination
261
+
262
+ SUMMARIZECOLUMNS returns only rows where **at least one measure is not BLANK**.
263
+
264
+ ```dax
265
+ // Only returns categories that have sales
266
+ EVALUATE
267
+ SUMMARIZECOLUMNS(
268
+ 'Product'[Category],
269
+ "Total Sales", [Total Sales]
270
+ )
271
+ ```
272
+
273
+ > **Important Distinction**: This elimination is about **measure values being blank**, NOT about excluding the **blank row from referential integrity violations**. If orphaned fact rows exist, they are grouped under the blank row member and **will appear** if aggregated measures are non-blank.
274
+
275
+ #### 2. Filter Arguments Must Be Table Expressions
276
+
277
+ ```dax
278
+ // Wrong:
279
+ SUMMARIZECOLUMNS('Product'[Category], 'Product'[Category] = "Bikes", "Total Sales", [Total Sales])
280
+
281
+ // Correct - Use TREATAS:
282
+ DEFINE
283
+ VAR _CategoryFilter = TREATAS({"Bikes"}, 'Product'[Category])
284
+ EVALUATE
285
+ SUMMARIZECOLUMNS('Product'[Category], _CategoryFilter, "Total Sales", [Total Sales])
286
+ ```
287
+
288
+ #### 3. Parameter Order is Strict
289
+
290
+ ```dax
291
+ SUMMARIZECOLUMNS(
292
+ // 1. GroupBy columns (any number)
293
+ 'Product'[Category],
294
+ 'Calendar'[Year],
295
+ // 2. Filters (any number of table expressions)
296
+ TREATAS({"Red", "Black"}, 'Product'[Color]),
297
+ FILTER(ALL('Calendar'[Year]), 'Calendar'[Year] >= 2020),
298
+ // 3. Aggregations/Measures (name-expression pairs)
299
+ "Total Sales", [Total Sales],
300
+ "Quantity", SUM('Sales'[Quantity])
301
+ )
302
+ ```
303
+
304
+ ### Common Usage Patterns
305
+
306
+ #### Basic Grouping with Measures
307
+
308
+ ```dax
309
+ EVALUATE
310
+ SUMMARIZECOLUMNS(
311
+ 'Product'[Category],
312
+ 'Calendar'[Year],
313
+ "Total Sales", [Total Sales],
314
+ "Total Quantity", SUM('Sales'[Quantity])
315
+ )
316
+ ORDER BY 'Calendar'[Year] DESC, [Total Sales] DESC
317
+ ```
318
+
319
+ #### With TREATAS Filter
320
+
321
+ ```dax
322
+ DEFINE
323
+ VAR _CategoryFilter = TREATAS({"Consumer Electronics"}, 'Product'[Category])
324
+ EVALUATE
325
+ SUMMARIZECOLUMNS(
326
+ 'Calendar'[Year],
327
+ 'Calendar'[Month],
328
+ _CategoryFilter,
329
+ "Total Quantity", SUM('Sales'[Order Quantity])
330
+ )
331
+ ORDER BY 'Calendar'[Year] DESC, 'Calendar'[Month] DESC
332
+ ```
333
+
334
+ #### With FILTER + ALL for Ranges
335
+
336
+ ```dax
337
+ DEFINE
338
+ VAR _YearFilter = FILTER(ALL('Calendar'[Year]), 'Calendar'[Year] >= 2022 && 'Calendar'[Year] <= 2023)
339
+ EVALUATE
340
+ SUMMARIZECOLUMNS('Calendar'[Year], _YearFilter, "Total Sales", [Total Sales])
341
+ ORDER BY 'Calendar'[Year] DESC
342
+ ```
343
+
344
+ #### Top N with SUMMARIZECOLUMNS
345
+
346
+ ```dax
347
+ DEFINE
348
+ VAR _ProductSales = SUMMARIZECOLUMNS('Product'[Name], "Sales", [Total Sales])
349
+ EVALUATE
350
+ TOPN(10, _ProductSales, [Sales], DESC)
351
+ ORDER BY [Sales] DESC
352
+ ```
353
+
354
+ #### Filter Only (No GroupBy Columns)
355
+
356
+ Returns a single-row result with aggregated values.
357
+
358
+ ```dax
359
+ DEFINE
360
+ VAR __filtered_products = FILTER(ALL('Product'[ProductID]), 'Product'[Category] = "Electronics")
361
+ EVALUATE
362
+ SUMMARIZECOLUMNS(__filtered_products, "Filtered Count", COUNTROWS('Product'))
363
+ ```
364
+
365
+ ### SUMMARIZECOLUMNS vs SUMMARIZE
366
+
367
+ | Aspect | SUMMARIZECOLUMNS | SUMMARIZE |
368
+ |--------|------------------|-----------|
369
+ | **Use for** | Aggregations with measures | Distinct column combinations only |
370
+ | **Blank measure elimination** | Auto-eliminates rows where ALL measures are BLANK | Keeps all combinations |
371
+ | **Performance** | Optimized for queries | Less optimized |
372
+ | **Filter params** | Accepts table filters | No filter parameters |
373
+
374
+ Use SUMMARIZECOLUMNS when you need aggregations. Use SUMMARIZE when you only need distinct combinations of column values.
375
+
376
+ ## ALL & ALLEXCEPT
377
+
378
+ ### ALL Function
379
+
380
+ Removes filters from a table or column(s), or returns all values as a table regardless of filter context.
381
+
382
+ > **Note**: This function has two distinct usages with different behaviors.
383
+
384
+ #### ALL as CALCULATE Modifier (Filter Removal)
385
+
386
+ ```dax
387
+ CALCULATE(<Expression>, ALL(<TableName>))
388
+ CALCULATE(<Expression>, ALL(<ColumnName>[, <ColumnName>, ...]))
389
+ CALCULATE(<Expression>, ALL())
390
+ ```
391
+
392
+ When used as a filter argument in CALCULATE:
393
+ - **Does NOT return a table** — only removes filters from filter context
394
+ - Clears filters on specified table or column(s)
395
+ - `ALL()` with no arguments removes all filters from all tables
396
+ - `REMOVEFILTERS` is functionally equivalent in this context
397
+
398
+ **Percentage of Total:**
399
+
400
+ ```dax
401
+ Sales % of Total = DIVIDE(
402
+ SUM(Sales[Amount]),
403
+ CALCULATE(SUM(Sales[Amount]), ALL(Product))
404
+ )
405
+ ```
406
+
407
+ **Remove Filter on Specific Column(s):**
408
+
409
+ ```dax
410
+ Sales All Colors = CALCULATE([Sales Amount], ALL(Product[Color]))
411
+ ```
412
+
413
+ **Grand Total Across All Dimensions:**
414
+
415
+ ```dax
416
+ Database Grand Total = CALCULATE([Sales Amount], ALL())
417
+ ```
418
+
419
+ | Pattern | Formula |
420
+ |---------|---------|
421
+ | Grand total | `CALCULATE([Measure], ALL(Table))` |
422
+ | % of total | `DIVIDE([Measure], CALCULATE([Measure], ALL(Table)))` |
423
+ | Ignore specific filter | `CALCULATE([Measure], ALL(Table[Column]))` |
424
+
425
+ #### ALL as Table Function (Returns Rows)
426
+
427
+ When used as a table expression:
428
+ - **Returns a table** containing all rows/values, ignoring filter context
429
+ - Includes blank row for invalid relationships
430
+ - Can be used with iterators (SUMX, FILTER, etc.)
431
+
432
+ **Ranking Pattern:**
433
+
434
+ ```dax
435
+ Product Rank = RANKX(ALL(Product[Product Name]), [Sales Amount])
436
+ ```
437
+
438
+ **Iteration Over All Values:**
439
+
440
+ ```dax
441
+ Max Sales Any Product = MAXX(ALL(Product), [Sales Amount])
442
+ ```
443
+
444
+ **Count All Values:**
445
+
446
+ ```dax
447
+ Total Product Count = COUNTROWS(ALL(Product))
448
+ ```
449
+
450
+ #### Key Distinction
451
+
452
+ | Usage Context | Returns | Behavior |
453
+ |---------------|---------|----------|
454
+ | Inside CALCULATE as filter argument | Nothing (modifier only) | Removes filters from context |
455
+ | Anywhere else (iterator, variable, table expression) | Table of rows | Returns all rows ignoring filters |
456
+
457
+ Notes:
458
+ - Always includes blank row for invalid relationships (use `ALLNOBLANKROW` to exclude)
459
+ - `ALL()` with no arguments ONLY works inside CALCULATE as modifier
460
+
461
+ ### ALLEXCEPT Function
462
+
463
+ Removes all filters from a table except for specified columns.
464
+
465
+ #### ALLEXCEPT as CALCULATE Modifier
466
+
467
+ ```dax
468
+ CALCULATE(<Expression>, ALLEXCEPT(<Table>, <Column1>[, <Column2>, ...]))
469
+ ```
470
+
471
+ When used as a filter argument in CALCULATE:
472
+ - **Does NOT return a table** — only modifies filter context
473
+ - Clears all filters on the specified table
474
+ - Retains filters ONLY on the listed columns
475
+
476
+ **Percentage of Parent Group:**
477
+
478
+ ```dax
479
+ % of Continent =
480
+ VAR CurrentSales = [Sales Amount]
481
+ VAR ContinentSales = CALCULATE(
482
+ [Sales Amount],
483
+ ALLEXCEPT(Customer, Customer[Continent])
484
+ )
485
+ RETURN DIVIDE(CurrentSales, ContinentSales)
486
+ ```
487
+
488
+ **Subtotal Pattern:**
489
+
490
+ ```dax
491
+ Category Subtotal = CALCULATE(
492
+ [Sales Amount],
493
+ ALLEXCEPT(Product, Product[Category])
494
+ )
495
+ ```
496
+
497
+ #### ALLEXCEPT vs ALL + VALUES
498
+
499
+ ```dax
500
+ // Using ALLEXCEPT — preserves existing Continent filters
501
+ CALCULATE([Sales], ALLEXCEPT(Customer, Customer[Continent]))
502
+
503
+ // Using ALL + VALUES — adds current Continent(s) as a new filter
504
+ CALCULATE([Sales], ALL(Customer), VALUES(Customer[Continent]))
505
+ ```
506
+
507
+ **Critical Difference**: ALLEXCEPT preserves existing filters; ALL + VALUES adds the current values as a new filter. Use ALL + VALUES when you need the parent group total. Use ALLEXCEPT only when an explicit filter already exists on the column you want to preserve.
508
+
509
+ #### ALLEXCEPT as Table Function
510
+
511
+ ```dax
512
+ // Count products in current category regardless of other filters
513
+ Products in Category =
514
+ VAR CategoryProducts = ALLEXCEPT(Product, Product[Category])
515
+ RETURN COUNTROWS(CategoryProducts)
516
+ ```
517
+
518
+ ## TREATAS
519
+
520
+ TREATAS takes a table expression and remaps its columns as if they were columns that already exist in the data model. It applies a virtual relationship between the input table and the target columns without requiring an actual relationship.
521
+
522
+ ### Syntax
523
+
524
+ ```dax
525
+ TREATAS(<table_expression>, <column>[, <column>]...)
526
+ ```
527
+
528
+ - **table_expression**: A table expression that returns values to be mapped
529
+ - **column**: Fully qualified column references. Count must match the table expression's column count.
530
+
531
+ Due to auto-exist semantics, only rows where the value combinations actually exist in the target columns are retained.
532
+
533
+ ### Examples
534
+
535
+ #### Simple Column Mapping
536
+
537
+ ```dax
538
+ CALCULATE([Sales Amount], TREATAS({"Red", "Blue"}, Product[Color]))
539
+ ```
540
+
541
+ #### Multi-Column Mapping
542
+
543
+ ```dax
544
+ CALCULATETABLE(
545
+ Sales,
546
+ TREATAS({(2023, 1), (2023, 2)}, Calendar[Year], Calendar[Quarter])
547
+ )
548
+ ```
549
+
550
+ #### In SUMMARIZECOLUMNS (Most Common Usage)
551
+
552
+ TREATAS is the preferred way to create filter arguments for SUMMARIZECOLUMNS.
553
+
554
+ ```dax
555
+ DEFINE
556
+ VAR _CategoryFilter = TREATAS({"Electronics", "Computers"}, 'Product'[Category])
557
+ EVALUATE
558
+ SUMMARIZECOLUMNS(
559
+ 'Product'[Name],
560
+ _CategoryFilter,
561
+ "Sales", [Total Sales]
562
+ )
563
+ ```
564
+
565
+ #### Filtering with Dynamic Values
566
+
567
+ ```dax
568
+ DEFINE
569
+ VAR _TopCategories = TOPN(3, VALUES('Product'[Category]), [Total Sales])
570
+ VAR _CategoryFilter = TREATAS(_TopCategories, 'Product'[Category])
571
+ EVALUATE
572
+ SUMMARIZECOLUMNS('Product'[Name], _CategoryFilter, "Sales", [Total Sales])
573
+ ```
574
+
575
+ #### Virtual Relationships
576
+
577
+ ```dax
578
+ CALCULATE(
579
+ [Total Sales],
580
+ TREATAS(VALUES(BudgetTable[ProductID]), Product[ProductID])
581
+ )
582
+ ```
583
+
584
+ ### Key Points
585
+
586
+ - Creates a virtual relationship for filtering purposes
587
+ - Values that don't exist in the target column are automatically filtered out (auto-exist)
588
+ - Most commonly used with SUMMARIZECOLUMNS as a filter argument
589
+ - Column count in table expression must match number of target columns
590
+ - Replaces older patterns like INTERSECT for applying dynamic filters
591
+
592
+ ## Common Mistakes
593
+
594
+ ### 1. Using Reserved Keywords Incorrectly
595
+
596
+ #### As Variable Names
597
+
598
+ Reserved keywords cannot be used as variable names in VAR statements.
599
+
600
+ ```dax
601
+ // Wrong: SUM is a reserved keyword
602
+ Total Sales =
603
+ VAR SUM = [Sales Amount]
604
+ RETURN SUM
605
+
606
+ // Correct: Use prefixed name
607
+ Total Sales =
608
+ VAR _TotalSales = [Sales Amount]
609
+ RETURN _TotalSales
610
+ ```
611
+
612
+ #### As Table Names
613
+
614
+ Many common table names like "Product", "Date", "Order" are also DAX reserved keywords. When a table name conflicts with a reserved keyword, enclose it in single quotes.
615
+
616
+ ```dax
617
+ // Wrong: PRODUCT is a reserved keyword
618
+ Total Products = COUNTROWS(Product)
619
+
620
+ // Correct: Single quotes escape the table name
621
+ Total Products = COUNTROWS('Product')
622
+
623
+ // Wrong: DATE is a reserved keyword
624
+ Sales This Year = CALCULATE([Sales Amount], Date[Year] = 2024)
625
+
626
+ // Correct:
627
+ Sales This Year = CALCULATE([Sales Amount], 'Date'[Year] = 2024)
628
+ ```
629
+
630
+ **Common table names that are keywords**: Product, Date, Order, Currency, Time, Calendar
631
+
632
+ **Best Practice**: Always quote table names with single quotes for all table references, even if not currently a keyword.
633
+
634
+ ### 2. Incorrect Column Reference from Table Variables
635
+
636
+ You cannot directly project a single column from a table variable using `_varTable[Column]` syntax.
637
+
638
+ ```dax
639
+ // Wrong:
640
+ VAR _modelInfo = INFO.MODEL()
641
+ VAR _discouraged = _modelInfo[DiscourageImplicitMeasures]
642
+ RETURN _discouraged
643
+
644
+ // Correct: Use SUMMARIZE
645
+ VAR _modelInfo = INFO.MODEL()
646
+ VAR _discouraged = SUMMARIZE(_modelInfo, [DiscourageImplicitMeasures])
647
+ RETURN _discouraged
648
+ ```
649
+
650
+ ```dax
651
+ // Wrong:
652
+ VAR _products = FILTER('Product', 'Product'[Category] = "Bikes")
653
+ RETURN _products[ProductName]
654
+
655
+ // Correct: Reference columns in iterator functions
656
+ VAR _products = FILTER('Product', 'Product'[Category] = "Bikes")
657
+ RETURN CONCATENATEX(_products, 'Product'[ProductName], ", ")
658
+ ```
659
+
660
+ ### 3. Incorrect String Literal Escaping
661
+
662
+ DAX uses doubled double quotes for escaping, not backslash.
663
+
664
+ ```dax
665
+ // Wrong: Backslash escape doesn't work in DAX
666
+ "He said \"Hello\""
667
+
668
+ // Correct: Two double quotes = one quote in the string
669
+ "He said ""Hello"""
670
+ ```
671
+
672
+ ## BLANK Semantics
673
+
674
+ ### Overview
675
+
676
+ BLANK is a special value in DAX that represents "no value". It is conceptually similar to SQL NULL but behaves very differently in expressions and comparisons.
677
+
678
+ ### Why BLANK Matters: SUMMARIZECOLUMNS Non-Empty Semantics
679
+
680
+ SUMMARIZECOLUMNS has **non-empty semantics**: a row is returned only if at least one measure returns a non-BLANK value.
681
+
682
+ **The Result Space Explosion Problem:**
683
+
684
+ ```dax
685
+ EVALUATE
686
+ SUMMARIZECOLUMNS(
687
+ 'Product'[Name],
688
+ 'Customer'[Name],
689
+ "Sales", [Sales]
690
+ )
691
+ ```
692
+
693
+ If `[Sales]` is `SUM('Sales'[Amount])`: Only combinations with actual sales records are returned.
694
+ If `[Sales]` is `SUM('Sales'[Amount]) + 0`: The `+ 0` converts BLANK to 0, making every row non-empty. ALL combinations are returned — potentially trillions of rows!
695
+
696
+ **Functions that return BLANK by design** (to prevent result explosion): COUNTROWS (empty table), SUM/AVERAGE (no rows), DIVIDE (division by zero).
697
+
698
+ ### Key Difference from SQL NULL
699
+
700
+ | Behavior | SQL NULL | DAX BLANK |
701
+ |----------|----------|-----------|
702
+ | Addition | NULL + 4 = NULL | BLANK() + 4 = 4 |
703
+ | Subtraction | NULL - 4 = NULL | BLANK() - 4 = -4 |
704
+ | Multiplication | NULL * 4 = NULL | BLANK() * 4 = BLANK |
705
+ | Division | 4 / NULL = NULL | 4 / BLANK() = Infinity |
706
+ | Equality | NULL = NULL is UNKNOWN | BLANK() = BLANK() is TRUE |
707
+ | String concat | NULL \|\| 'A' = NULL | BLANK() & "A" = "A" |
708
+
709
+ ### BLANK Propagation Rules
710
+
711
+ **Operations where BLANK propagates (returns BLANK):**
712
+
713
+ ```dax
714
+ BLANK() * 4 // BLANK (multiplication)
715
+ BLANK() / 4 // BLANK (division)
716
+ BLANK() / BLANK() // BLANK
717
+ -BLANK() // BLANK (negation)
718
+ BLANK() + BLANK() // BLANK (both operands blank)
719
+ BLANK() - BLANK() // BLANK (both operands blank)
720
+ ```
721
+
722
+ **Operations where BLANK converts to 0 or empty string:**
723
+
724
+ ```dax
725
+ BLANK() + 4 // 4 (BLANK converted to 0)
726
+ BLANK() - 4 // -4 (BLANK converted to 0)
727
+ 4 / BLANK() // Infinity (BLANK converted to 0)
728
+ BLANK() & "A" // "A" (BLANK converted to empty string)
729
+ ```
730
+
731
+ ### Comparison Semantics
732
+
733
+ #### Standard Equality (=) — Equivalent Values
734
+
735
+ BLANK is equivalent to 0, empty string "", FALSE, DateTime origin:
736
+
737
+ ```dax
738
+ BLANK() = 0 // TRUE
739
+ BLANK() = "" // TRUE
740
+ BLANK() = FALSE // TRUE
741
+ BLANK() = BLANK() // TRUE
742
+ ```
743
+
744
+ #### Strict Equality (==), IN, SWITCH — Exact Match
745
+
746
+ Only identical values match:
747
+
748
+ ```dax
749
+ BLANK() == 0 // FALSE
750
+ BLANK() == "" // FALSE
751
+ BLANK() == BLANK() // TRUE
752
+ BLANK() IN {0} // FALSE
753
+ BLANK() IN {BLANK()} // TRUE
754
+ ```
755
+
756
+ #### Comparison Operators
757
+
758
+ BLANK is treated as 0:
759
+
760
+ ```dax
761
+ BLANK() < 1 // TRUE (0 < 1)
762
+ BLANK() > -1 // TRUE (0 > -1)
763
+ ```
764
+
765
+ ### Testing for BLANK
766
+
767
+ Use ISBLANK (not equality to BLANK):
768
+
769
+ ```dax
770
+ // Wrong: matches BLANK, 0, and ""
771
+ IF([Value] = BLANK(), "is blank", "has value")
772
+
773
+ // Correct:
774
+ IF(ISBLANK([Value]), "is blank", "has value")
775
+ IF([Value] == BLANK(), "is blank", "has value")
776
+ ```
777
+
778
+ ### SWITCH Behavior
779
+
780
+ SWITCH uses exact match semantics (like == and IN):
781
+
782
+ ```dax
783
+ SWITCH(BLANK(),
784
+ 0, "zero", // Not matched
785
+ FALSE, "false", // Not matched
786
+ BLANK(), "blank", // Matched!
787
+ "other")
788
+ // Returns: "blank"
789
+ ```
790
+
791
+ ### Safe Division with DIVIDE
792
+
793
+ ```dax
794
+ DIVIDE(BLANK(), 4) // BLANK
795
+ DIVIDE(4, BLANK()) // BLANK (not Infinity!)
796
+ DIVIDE(BLANK(), BLANK()) // BLANK
797
+ ```
798
+
799
+ **Anti-Pattern Warning:**
800
+
801
+ ```dax
802
+ // BAD: Can cause result space explosion in SUMMARIZECOLUMNS queries
803
+ DIVIDE([Sales], [Quantity], 0)
804
+
805
+ // GOOD: Let DIVIDE return BLANK (the default)
806
+ DIVIDE([Sales], [Quantity])
807
+ ```
808
+
809
+ ### COALESCE for Default Values
810
+
811
+ ```dax
812
+ COALESCE([Measure], 0) // Returns 0 if measure is BLANK
813
+ COALESCE([Value1], [Value2], [Value3], "default") // First non-BLANK
814
+ ```
815
+
816
+ ### Blank Row Concept
817
+
818
+ The **blank row** is separate from the BLANK value. It's a special row created when fact table rows reference non-existent dimension keys.
819
+
820
+ ```dax
821
+ // VALUES includes blank row from invalid relationships
822
+ VALUES(Product[ProductKey]) // May include blank row
823
+
824
+ // DISTINCT never includes blank row
825
+ DISTINCT(Product[ProductKey]) // Never includes blank row
826
+
827
+ // ALLNOBLANKROW removes only the special blank row
828
+ ALLNOBLANKROW(Product) // Excludes blank row from invalid relationships
829
+ ```
830
+
831
+ ### Sort Order
832
+
833
+ BLANK always sorts as the **lowest** value (first in ASC, last in DESC). BLANK sorts BEFORE zero in numeric sorting.
834
+
835
+ | Value | ASC Position | DESC Position |
836
+ |-------|-------------|---------------|
837
+ | -1 | 1st | Last |
838
+ | BLANK | 2nd | 3rd |
839
+ | 0 | 3rd | 2nd |
840
+ | 1 | 4th | 1st |
841
+
842
+ **Key Insight**: `BLANK() = 0` is TRUE (equality), but BLANK sorts before 0 (sort order).
843
+
844
+ ### Best Practices
845
+
846
+ 1. **Let measures return BLANK** — Never add `+ 0` or use `DIVIDE(x, y, 0)` just to display 0
847
+ 2. **Use ISBLANK or == for testing BLANK** — Standard equality (=) treats BLANK as equivalent to 0, empty string, and FALSE
848
+ 3. **Use COALESCE sparingly** — Only in display-layer measures, not in measures used for filtering or grouping
849
+
850
+ ### Related Functions
851
+
852
+ | Function | Purpose |
853
+ |----------|---------|
854
+ | BLANK() | Returns a blank value |
855
+ | ISBLANK(value) | Tests if value is BLANK |
856
+ | COALESCE(value1, value2, ...) | Returns first non-BLANK value |
857
+ | DIVIDE(num, denom [, alt]) | Safe division, returns BLANK for division by zero |
858
+ | VALUES(column) | Returns distinct values including blank row |
859
+ | DISTINCT(column) | Returns distinct values excluding blank row |
860
+ | ALLNOBLANKROW(table) | Removes blank row from filter context |
861
+ | FIRSTNONBLANK(column, expr) | First value where expression is not blank |
862
+ | LASTNONBLANK(column, expr) | Last value where expression is not blank |