Avatar of Queennie L
Queennie L
 asked on

Get Top 20 by value per name

Hello Experts,

How do I get the top 20 by Charges for each Store Name ?

I know this is just easy but I cannot figure it out.

See example attached.

Thank you for all your help.
GetTheTop20ChargesByStoreName.xlsx
Microsoft SQL ServerSQL

Avatar of undefined
Last Comment
Scott Pletcher

8/22/2022 - Mon
Scott Pletcher

SELECT StoreName, Charges, Payments, Adjustments, AccountsReceivable
FROM (
    SELECT *, ROW_NUMBER() OVER(PARTITION BY StoreName ORDER BY Charges DESC) AS row_num
    FROM dbo.your_table_name
) AS query1
WHERE row_num <= 20 /*CORRECTION from earlier code, which had row_num = 1*/
ORDER BY StoreName, Charges DESC


Queennie L

ASKER
@Scott,

Thank you for your help.

Your query is perfectly correct but I asked the wrong question.

Is there a way I can reverse if Top 20 by Store Name on Charges?

Show only top 20 Store Name. I know my example has only 4 store name.


Thank you.
ASKER CERTIFIED SOLUTION
Scott Pletcher

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
Scott Pletcher

Notice too that I had to make a correction to my other code, maybe that would give you the actual solution you need too.
I started with Experts Exchange in 2004 and it's been a mainstay of my professional computing life since. It helped me launch a career as a programmer / Oracle data analyst
William Peck
Queennie L

ASKER
Sorry about that.
Queennie L

ASKER
@Scott:
Thank you for all your help.
Scott Pletcher

No worries, glad it helped.
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.