Sub topic 11
Counting Rows of a Filtered Table with COUNTROWS and FILTER
This chapter assumes you can already write a basic measure in the formula bar. You should know that SUM and COUNTROWS evaluate in the filter context created by visuals and slicers. You should also be comfortable with a data model that has a Sales table with a numeric SalesAmount column, where each row is one order line.
By the end, you will be able to count only the rows that meet a condition. You will also know why the count still responds to slicers, what happens when no rows match, and when to choose a different pattern.
Why COUNTROWS takes a table
You have used COUNTROWS(Sales) to count order lines. The argument is a table, and Sales is the simplest table expression, a direct reference to a table in the model.
Any expression that returns a table is also valid. COUNTROWS does not care where the table comes from. It counts the rows it receives. So if you can build a table that holds only the rows you want, COUNTROWS counts them.
FILTER builds that table.
What FILTER does
FILTER takes a table and a condition, and returns a table:
FILTER(<table>, <condition>)It goes through the input table one row at a time. For each row, it evaluates the condition. If the condition is true, the row stays in the result. If it is false or blank, the row is dropped.
Two points matter here:
FILTERreturns a table, not a number. You cannot put a bareFILTER(...)in a measure. You must wrap it in a function that turns a table into a value, such asCOUNTROWS.FILTERis an iterator. The condition is evaluated in a row context, which is why you can writeSales[SalesAmount]in it and get the amount of the current row.
Combining the two gives the measure from the plan:
Large Order Lines = COUNTROWS(FILTER(Sales, Sales[SalesAmount] > 1000))Read it from the inside out. FILTER keeps the Sales rows whose SalesAmount is greater than 1000. COUNTROWS counts what is left.
A worked example
Suppose the Sales table has six rows:
| Row | Region | SalesAmount |
|---|---|---|
| 1 | West | 450 |
| 2 | West | 1200 |
| 3 | East | 2500 |
| 4 | East | 800 |
| 5 | East | 1000 |
| 6 | West | 1500 |
Create these measures, one after another:
Total Sales = SUM(Sales[SalesAmount])Order Lines = COUNTROWS(Sales)Large Order Lines = COUNTROWS(FILTER(Sales, Sales[SalesAmount] > 1000))Place Region on the rows of a table visual and add the three measures. You should see these values:
| Region | Total Sales | Order Lines | Large Order Lines |
|---|---|---|---|
| East | 4300 | 3 | 1 |
| West | 3150 | 3 | 2 |
| Total | 7450 | 6 | 3 |
Row 5 has a SalesAmount of exactly 1000. The condition is > 1000, so that row does not qualify. East has one large line (2500), and West has two (1200 and 1500). If you want to include the boundary, change the operator to >=. Off-by-one errors at the boundary are the most common mistake with threshold conditions, so decide on purpose which side the boundary value belongs to.
How the filter context still applies
The Large Order Lines measure is not a global count. It respects the same filters as every other measure. The following diagram shows why.
The first thing the engine does for each cell in a visual is apply the filter context. For the East row in your table, only East rows are visible in Sales. When FILTER receives Sales, it receives only those visible rows. It filters them further, and COUNTROWS counts the survivors.
So if you add a slicer for Region and select West, the grand total of Large Order Lines changes from 3 to 2. You did not write any slicer logic. The two filters stack: the slicer narrows the table, and your condition narrows it again.
Combining conditions
You can combine conditions inside FILTER with && for AND and || for OR:
Large West Order Lines =
COUNTROWS(
FILTER(
Sales,
Sales[SalesAmount] > 1000 && Sales[Region] = "West"
)
)On the sample data this returns 2. Be careful with the interaction with the visual. If the same visual is split by Region, the East row of this measure shows blank, because no East rows survive the condition. That is correct behavior, not a bug.
Ignoring filters on purpose
Sometimes you want the count across all rows, regardless of slicers. ALL returns a table with the filters removed:
Large Order Lines (All Regions) =
COUNTROWS(FILTER(ALL(Sales), Sales[SalesAmount] > 1000))Now every cell shows 3, even in the East row. This is useful as a denominator for a share of the overall count, but use it deliberately. It is also an early look at a larger topic. Changing filter context is the main job of CALCULATE, which later chapters cover.
Building on the filtered count
A filtered count is most useful when you combine it with other measures. Reference it the way you reference any measure, by name in square brackets.
Large Line Share = DIVIDE([Large Order Lines], [Order Lines])DIVIDE returns BLANK instead of an error when [Order Lines] is zero or blank. Format the measure as a percentage in the Measure tools tab. On the sample data it returns 50% overall, 33.3% for East (1 of 3), and 66.7% for West (2 of 3).
This works because both measures are evaluated in the same filter context. For the East row, the numerator counts large East lines and the denominator counts all East lines. You do not need to pass the region to either measure.
Avoiding hard-coded thresholds
The number 1000 is buried in the formula. If you use it in several measures, you have to update each one when the business changes the definition of a large line. A VAR (variable) gives the value a name and keeps it in one place:
Large Order Lines (Named Threshold) =
VAR Threshold = 1000
RETURN
COUNTROWS(FILTER(Sales, Sales[SalesAmount] > Threshold))VAR declares a named value inside the measure. RETURN marks the expression that produces the result. The result is the same as before, but the formula now explains itself.
Variables are scoped to one measure. For a threshold shared across measures, you would store it in a single measure of its own, such as Large Line Threshold = 1000, and reference [Large Line Threshold] from the others. The formulas then change in one place. A what-if parameter is another option when report users need to change the number themselves.
When no rows match
Suppose you select a slicer value for which no row exceeds 1000. FILTER returns an empty table, and COUNTROWS of an empty table returns BLANK, not 0. In a table visual, the row may disappear entirely, because Power BI hides rows where all measures are blank. In a card, the card shows an empty value.
Whether that is acceptable depends on the report. If you need a visible zero, add zero to the result:
Large Order Lines (Zero if None) =
COUNTROWS(FILTER(Sales, Sales[SalesAmount] > 1000)) + 0Adding + 0 converts BLANK to 0. This has a side effect. The measure now returns 0 for every combination of filters, including combinations that have no data at all, such as dates or categories with no sales. A visual that used to show only relevant rows may now show every member with a 0. Test the visual after you make this change.
FILTER over the right table
FILTER counts rows of whatever table you give it. This catches people out in a model with several related tables.
Consider Products related to Sales through a product key. This measure counts products, not sales lines:
Products With Large Lines =
COUNTROWS(FILTER(Products, Products[ListPrice] > 1000))The condition uses Products[ListPrice], so the table passed to FILTER is Products, and the count is a count of products. If you wanted order lines for expensive products, you would need a different pattern, because Sales[SalesAmount] and Products[ListPrice] live in different tables. A condition in FILTER can use columns from the table being filtered. Columns from another table need related-table functions or a different approach.
Keep this rule in mind: the table argument of FILTER sets what is being counted, and the condition must be about columns of that table.
FILTER versus a Boolean filter in CALCULATE
You will see another way to write the same count:
Large Order Lines (CALCULATE) =
CALCULATE(COUNTROWS(Sales), Sales[SalesAmount] > 1000)On the sample data, this returns the same numbers as the FILTER version. The two forms differ in how they work:
| Aspect | `COUNTROWS(FILTER(...))` | `CALCULATE(COUNTROWS(...), condition)` |
|---|---|---|
| How the condition is applied | Row by row over the table | As a filter on the column |
| Condition can use a measure | Yes | Not directly in a simple Boolean filter |
| Typical cost on large tables | Higher, because it iterates | Usually lower |
| Works for conditions across several columns of one row | Yes | Needs care |
For a simple condition on one column, the CALCULATE form is usually the better choice on large tables. Use FILTER when the condition compares columns in the same row, or when you are learning how table expressions flow into COUNTROWS. This chapter uses FILTER because it shows clearly that COUNTROWS counts any table.
Common mistakes
- Using FILTER alone as a measure. A measure must return a single value.
FILTER(Sales, ...)returns a table and produces an error. Wrap it inCOUNTROWSor another aggregation. - Getting the boundary wrong.
>excludes the boundary value and>=includes it. Check against a row you know sits on the boundary. - Expecting a global count. The measure respects slicers and visual filters. If you see a different number than a colleague's calculation, compare the filters first.
- Comparing text with the wrong case or spelling. Text comparison with
=in DAX is not case-sensitive, but a misspelled value silently matches nothing and gives BLANK. - Counting the wrong table. Check that the first argument of
FILTERis the table whose rows you intend to count.
Checking your work
A reliable habit is to verify a filtered count against a visible list of rows. Add a table visual of the Sales rows with SalesAmount, and apply a visual-level filter of SalesAmount greater than 1000. The number of rows in that table should equal your measure. If the two disagree, the cause is usually the boundary, a slicer you forgot, or the wrong table.
Exercise
Using the six-row sample table in this chapter, write a measure that counts order lines with a SalesAmount of 1000 or more, and give its value for the East region and for the grand total.
Show answer
Large Or Equal Order Lines = COUNTROWS(FILTER(Sales, Sales[SalesAmount] >= 1000)). East has two qualifying rows (2500 and 1000), so the East value is 2. West has two (1200 and 1500), so the grand total is 4.
Exercise
A slicer selects a region where no row has a SalesAmount above 1000. What does Large Order Lines show, and how can you make it show 0 instead?
Show answer
It shows BLANK, because FILTER returns an empty table and COUNTROWS of an empty table returns BLANK. Add zero to the result, as in COUNTROWS(FILTER(Sales, Sales[SalesAmount] > 1000)) + 0, and check that visuals do not become cluttered with zero rows.
Exercise
Write a measure for the share of large order lines that ignores slicers in the denominator, so it shows each region's large lines as a share of all order lines in the whole table.
Show answer
Large Share Of All Lines = DIVIDE([Large Order Lines], COUNTROWS(ALL(Sales))). The numerator respects the region filter, and ALL(Sales) removes it from the denominator. For West this gives 2 / 6, about 33.3%.