I have a table of results like this, where the usage of each item totals 100%:
| Item | Usage | Customer |
| ------------ | ------------ | ------------ |
| Item1 | 90 | Customer 1 |
| Item1 | 10 | Customer 2 |
| Item2 | 54 | Customer 3 |
| Item2 | 46 | Customer 2 |
| Item3 | 23 | Customer 4 |
| Item3 | 77 | Customer 5 |
From this, I want to only show the rows with the max usage of each item, to show the customer that used the most of the item, so my results would be:
Item | Usage | Customer |
---|---|---|
Item1 | 90 | Customer 1 |
Item2 | 54 | Customer 3 |
Item3 | 77 | Customer 5 |
I've tried using max and group by, but I can't seem to get it to return only the max usage rows, I always end up with all 6 rows due to the need to include the customer column. Is there anyway to achieve this?
2条答案
按热度按时间piok6c0g1#
You can allow the
ROW_NUMBER
window function to craft a ranking value for each of your items, ordered by usage. Then makeTOP(1) WITH TIES
filter values with respect to theORDER BY
clause, getting only the first value tied (row number = 1, or if you will, the greatest usage value for each item).Equivalently, you can compute the
ROW_NUMBER
window function first, then select all rows that have ranking = 1 in a subquery.Output:
Check the demo here .
Consider learning more about these SQL-Server tools at the corresponding linked web pages.
mf98qq942#
I have used data provided by you to create a SQLFIDDLE.
I want to only show the rows with the max usage of each item, to show the customer that used the most of the item.
This can be achieved as
This gives me the expected output as :
You can see the demo in SQLFIDDLE