Bootstrap

SQL根据字段分组并获取每个值的十条数据

使用SQL中的partition函数

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

查询结果

转载于:https://www.cnblogs.com/zoro-zero/p/10954781.html

3.查询每个平台下热榜歌曲各30条

select w.media_id 
from (
    select row_number () over (partition by b.platform order by a.play_count desc) rn,    ---以platform分组,分组内以play_count倒序排列求每组中各自的序号
        b.platform, a.play_count,a.media_id 
    from musems_music_play_count a 
		LEFT JOIN musems_media_information b on a.media_id = b.id 
    WHERE b.type = 1 AND b.state = 1 
) w
where w.rn <=30  -- 序号小于30
order by w.platform asc, w.play_count desc

;