这对SQL来说还很新-帮助将不胜感激。我有一个表Region,Month,Member ID,和Sales(每个成员多次交易)。我只想根据每个区域每个月的销售额之和来提取排名前2位的成员....所以本质上是:
Region
Month
Member ID
Sales
Region Month MemberID Sales ----------------------------------------- 1 1/1/2013 A $200 2 2/1/2013 B $300 1 1/1/2013 A $100 1 1/1/2013 B $50 2 1/1/2013 D $500 2 2/1/2013 C $200
成为:
Region Month Member ID Sales ----------------------------------------- 1 1/1/2013 A $300 1 1/1/2013 B $50 2 1/1/2013 D $500 2 1/1/2013 B $200
最终,将有10个地区,而我想每个月按会员列出前5名的销售额。
您可以执行以下操作row_number():
row_number()
select region, month, MemberId, sales from (select region, month, MemberId, sum(sales) as sales row_number() over (partition by region, month order by sum(sales) desc) as seqnum from table t group by region, month, MemberId ) t where seqnum <= 2;