Forum Discussion

LetsPBI's avatar
LetsPBI
New Member
6 years ago
Solved

Filter by top value per category while keeping all columns

Hi,

 

I'm quite newbie in PowerBI, and I put myself to a task that's proving a bit complicated:

 

I have two tables:

 

Products (Name is Unique)

NameCategoryProvider
ApplesFruitA
ButterDairyB
TomatoesVegetablesA
BananasFruitA
PearsFruitC
LettuceVegetablesD
MilkDairyE
CheeseDairyF
YogurtDairyG

 

Sales (Sale_Id is Unique)

ProductCitySaleDateTimeSale_Id
TomatoesA10003/06/202009:001
TomatoesA9001/06/202018:002
TomatoesA10002/06/202019:003
ApplesA12001/06/202012:004
ApplesB12001/06/202016:005
CheeseB20001/06/202014:006
YogurtB12501/06/202010:007

 

I need to create a table with all columns, that lists only the top sale for each Product/City. For equal Product/City/Sale, the chosen row should be the one with the earliest date/time. The pairs Product/City that do not have sales shall also be listed with sales data empty/null, something like this:

Name

CategoryProviderCitySaleDateTimeSale_Id
ApplesFruitAA12001/06/202012:004
ApplesFruitAB12001/06/202016:005
ButterDairyBA    
ButterDairyBB    
TomatoesVegetablesAA10002/06/202019:003
TomatoesVegetablesAB    
BananasFruitAA    
BananasFruitAB    
PearsFruitCA    
PearsFruitCB    
LettuceVegetablesDA    
LettuceVegetablesDB    
MilkDairyEA    
MilkDairyEB    
CheeseDairyFA    
CheeseDairyFB20001/06/202014:006
YogurtDairyGA    
YogurtDairyGB12501/06/202010:007

 

Sales table has millions of rows, I suppose that performance wise, the less times we merge into it the better.

 

It is also acceptable to create two tables, one per city. I almost solved the problem with a series of Merge and one Group By Max(Sale), but I still cannot avoid duplicates in the end table when the same Product/City have several sales with the same value which is also the top one. In the example above, I get two rows for Tomatoes in City A, for sale 1 and sale 3. If I tune the Group By adding Min(Date), Min(Time) and Min(Sale_Id), I lose the relational integrity, as I get only one line for Tomatoes in City A, but date 2020/06/01, time 09:00 and Sale_Id 1.

 

I also thought of creating a column with a binary value being 1 for each Max(Sale)/Min(Date and time)/Min(Sale_Id), but I would need some kind of MINIF, which I also don't know how to do.

 

I prefer a Power Query only solution, but I can live with a M/DAX combination. Is there a way to get the table (or tables) I need, if possible in a non overly complicated way?

 

Your help and expertise is highly appreciated!

António

2 Replies