如何根据另一列(ID)从列(金额)中选择前10个下降总计?
这就是我想要的结果:
(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.
感谢。
答案 0 :(得分:1)
试试这个:
;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
答案 1 :(得分:0)
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
答案 2 :(得分:0)
select * from t where id in
(select top 10 id from t group by id order by sum(Amount) desc)
如果您需要以sum(Amount)排序的最终结果,这里是一个查询:
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