2

This is the data I have:

Customer Sales
A 3
B 10
C 4
D 2
E 4

This is where I want to get:

# Top Customers Total Sales
1 10
2 14
3 18
4 21
5 23

I am trying to do this with ROW_NUMBER and OVER (a window function?):

SELECT 
  ROW_NUMBER() OVER (ORDER BY Sales DESC) AS '# TOP CUSTOMERS',
  SUM(Sales) OVER (ORDER BY Sales DESC) AS 'SUM SALES'
FROM Sales;

but I get this result:

# Top Customers Total Sales
1 10
2 18
3 18
4 21
5 23

Do I need to use DENSE_RANK or PARTITION BY? For what it's worth, I'm not even trying to rank or partition, I'm just trying order the rows, so trying to see if there's a simple solution.

2
  • 1
    OVER (ORDER BY Sales DESC, customer) to ensure the ordering never has duplicates and is deterministic... db-fiddle.com/f/7GwR7PQwYufFTEDGyu3JUH/0 Commented Sep 18, 2024 at 23:21
  • @MatBailie This works great, should have been obvious. Thanks Commented Sep 19, 2024 at 0:06

1 Answer 1

0

You should include Customer as well to make the row unique. See the image

SELECT 
  ROW_NUMBER() OVER (ORDER BY Sales DESC) AS '# TOP CUSTOMERS',
  SUM(Sales) OVER (ORDER BY  Sales DESC, Customer ASC ) AS 'SUM SALES'
FROM Sales;

Click me for results

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.