1、sql 語法
select m, n from ( select row_number () over (partition by m order by n desc) rn,--以m分組,分組內以n倒序排列求每組中各自的序號
m, n from table
where ... ) w where w.rn <=10;序號小於10 order by m, n desc
2、案例獲取每個月前十大客戶數據
原來數據
案例sql
select StatDate, OrderCount, AmountTotal, CustomerUnitPrice from ( select row_number () over (partition by t.StatDate order by t.AmountTotal desc) rn, *
from ( select
CONVERT(varchar(7), AuditTime, 120) StatDate, FBM_USER_ID CustomerId, Count(1) OrderCount, sum(isnull(FBM_BLL_BOOK_TOTAL,0)) AmountTotal, case when sum(isnull(FBM_BLL_BOOK_TOTAL,0)) >0 then Round((sum(isnull(FBM_BLL_BOOK_TOTAL,0)) / Count(1) + 0.0), 4) else 0 end as CustomerUnitPrice from F_CUST_BOOK_MSTR b where auditStatus=2 and AuditTime is not null
and AuditTime>='2017-06-01'
group by CONVERT(varchar(7), AuditTime, 120),FBM_USER_ID ) t ) tt where rn <=10
order by StatDate desc
查詢結果