0

如何根据另一列 (ID) 从一列 (Amount) 中选择前 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.

谢谢。

4

3 回答 3

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


SQL 小提琴演示

于 2012-08-30T11:45:02.350 回答
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

于 2012-08-30T11:43:02.230 回答
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
于 2012-08-30T11:43:03.270 回答