Reputation: 111
How do I select the top 10 descending totals from a column (Amount) based on another column (ID)?
This is what I'd like my desired results to look like:
(Top 1)
Row 1: ID: 9, Amount: 10, Total: 15
Row 2: ID: 9, Amount: 5, Total: 15
(Top 2)
Row 3: ID: 500, Amount: 14, Total: 14
(Top 3)
Row 4: ID: 27, Amount: 3, Total: 9
Row 5: ID: 27, Amount: 3, Total: 9
Row 6: ID: 27, Amount: 3, Total: 9 etc.
Thanks.
Upvotes: 0
Views: 167
Reputation: 24144
select * from t where id in
(select top 10 id from t group by id order by sum(Amount) desc)
if you need the final results to be ordered by sum(Amount) here is a query:
select t.*,t2.sum_amount from t
inner join (select top 10 id,sum(Amount) as sum_amount
from t
group by id
order by sum(Amount) desc) t2
on (t.Id = t2.id)
order by t2.Sum_amount desc ,id
Upvotes: 0
Reputation: 24116
try this:
;with cte as
(select *,
row_number() over(partition by ID order by Amount desc) as row_num
from your_table),
cte1 as(
select ID,SUM( Amount) as Total
from your_table
group by ID)
select top 10 c.ID,C.Amount,c1.Total
from cte c join cte1 c1
on c.ID=c1.ID
order by C1.Total desc
Upvotes: 1
Reputation: 5248
select Row, ID, Amount, Total
from
(
select Row, ID, Amount, Total
,rank() over (order by Total desc) as Rank
from t1
) rt
where Rank between 1 and 10
Upvotes: 0