Forum Discussion

smpa01's avatar
smpa01
Icon for Community Champion rankCommunity Champion
4 years ago
Solved

DAX to filter table based on TOPN aggregation

I have a table like this

 

| name | sale |
|------|------|
| a    | 1000 |
| a    | 1500 |
| b    | 2000 |
| b    | 1500 |
| c    | 2000 |
| c    | 2000 |
| d    | 5000 |

 

and I am trying to write a measure to utilize TOPN that would return the filter table based on TOP 2 sale by name.

I want to end up with this

 

| name | sale |
|------|------|
| d    | 5000 |
| c    | 4000 |

 

The equivalent SQL is following

 

declare @t1 as table (name varchar(1),sale int)
insert into @t1
select * from
(values('a',1000),('a',1500),('b',2000),('b',1500),('c',2000),('c',2000),('d',5000)) t(a,b)

;with cte1 as(
select name, SUM(sale) as sale
from @t1
group by name
)
select TOP 2 * from cte1
order by sale desc

 

 

 

But in DAX if I try the following

 

Measure =
CALCULATE (
    SUM ( 'Table'[sale] ),
    CALCULATETABLE (
        'Table',
        TOPN ( 2, VALUES ( 'Table'[name] ), CALCULATE ( SUM ( 'Table'[sale] ) ), DESC )
    )
)

 

it does not do anything

 

However, I can get to where I want to by using the following set up

 

But I am simply trying to undertand, if it is possible to filter the table using TOPN.

 

AlexisOlson  CNENFRNL 

5 Replies