Skip to main content
Announcements
Introducing Qlik Answers: A plug-and-play, Generative AI powered RAG solution. READ ALL ABOUT IT!
cancel
Showing results for 
Search instead for 
Did you mean: 
gabormajdan
Contributor
Contributor

Creating average by unique countries

Hi All,

I want to create the average score of an HQ, based on its top 3 highest scoring subsidiaries. There is one condition: the top 3 has to be composed of unique countries, i.e. the average cannot contain more than 1 subsidiary based in the same country. If a such a case occurs, we will take the highest score into account. See the example below.

Here is the source data:

HQSubsidiaryCountryScore
HQ_1Company_AFRA6
HQ_1Company_BITA5
HQ_1Company_CFRA4
HQ_1Company_DGER2
HQ_2Company_EESP7
HQ_2Company_FITA4
HQ_2Company_GGER3
HQ_2Company_HESP2

The resulting table would look like this:

RankHQAverage Score
1.HQ_24.67
2.HQ_14.33

Notice that for HQ_1 we had to take the average of companies A, B and D, because A and C are both from France and A has the highest score. Therefore C was omitted. H was omitted because it is not in the top 3. (note: we don't have to deal with the dilemma of an HQ having subsidiaries from only 1 country)

I have the following piece of code, that does the job of picking the top 3 of any HQ, but I cannot get it to exclude a duplicate country.

avg(

    if(

        aggr(num(rank(sum(Score),1)), HQ, Subsidiary) < 4,

        sum(Score)

    )

)

Thanks in advance for your help!


Gabor

1 Solution

Accepted Solutions
Gysbert_Wassenaar

Try this: avg(aggr(if(rank(max(Score))<4,max(Score)),Country,HQ))


talk is cheap, supply exceeds demand

View solution in original post

3 Replies
Gysbert_Wassenaar

Try this: avg(aggr(if(rank(max(Score))<4,max(Score)),Country,HQ))


talk is cheap, supply exceeds demand
swuehl
MVP
MVP

I would use

=avg(aggr(if(rank(max(Score))<4,max(Score)),HQ, Country))

gabormajdan
Contributor
Contributor
Author

Thanks! I had to tweak it a bit myself, because I gave a simplified version of the problem, but overall this was the right solution (in reality the Score is a lengthy calculation so I had to embed another aggr in the max, over Country, HQ and Company fields).

Something like this:

avg(aggr(if(rank(max(aggr(Score,Country,HQ,Company)),<4,max(aggr(Score,Country,HQ,Company))),Country,HQ))