sql server 獲取某一字段分組數據的前十條記錄


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

查詢結果

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM