0

別の列 (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.

ありがとう。

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 に答える