SQL中Group分組獲取Top N 方法實現

2022-03-22 10:18:38 字數 2366 閱讀 3360

有產品表,包含id,name,city,addtime四個字段,因報表需要按城市分組,統計每個城市的最新10個產品,便向該表中插入了100萬資料,做了如下系列測試:

create

table

[dbo

].[products](

[id][

int]

identity(1,1) not

null

,

[name][

nvarchar

](50) null

,

[addtime][

datetime

]null

,

[city][

nvarchar

](10) null,

constraint

[pk_products

]primary

keyclustered

( [id

]asc

)with (pad_index =

off, statistics_norecompute =

off, ignore_dup_key =

off, allow_row_locks =

on, allow_page_locks =

on) on

[primary])

on[primary

]

1、採用row_number方法,執行5次,平均下來8秒左右,速度最快。

select

no, id,name,city

from (select no =row_number() over (partition by city order

by addtime desc), *

from

products)t

where no<

11order

by city asc,addtime desc

select

distinct b.id,b.name,b.city from

products a

top10

*from products where city = a.city order

by addtime desc) b

3、採用count查詢,只執行了兩次,第一次執行到5分鐘時,取消任務執行了;第二次執行到13分鐘時,沒有hold住又直接停止了,實在無法忍受。

select id,name,city from

products a

where ( select

count(city) from products where a.city = city and addtime>a.addtime) <

10order

by city asc,addtime desc

4、採用游標方法,這個最後測試的,執行了5次,每次都是10秒完成,感覺還不錯。

declare

@city

nvarchar(10

)create

table #top(id int,name nvarchar(50),city nvarchar(10),addtime datetime

)declare mycursor cursor

forselect

distinct city from products order

by city asc

open

mycursor

fetch

next

from mycursor into

@city

while

@@fetch_status=0

begin

insert

into #top

select

top10 id,name,city,addtime from products where city =

@city

fetch

next

from mycursor into

@city

endclose

mycursor

deallocate

mycursor

select

*from #top

order

by city asc,addtime desc

drop

table #top

通過上述對比不難發現,在面臨group獲取top n場景時,可以首選row_number,游標cursor其次,另外兩個就基本不考慮了,資料量大的時候根本沒法使用。

solr分組查詢GROUP

order處理 if order params sort order group處理 if group else 執行查詢 response this search where,limit start,limit end,params 引數 型別說明 group 布林值設為true,表示結果需要分組...

盡量在SQL中Group

對於彙總型別的分析報表,在報表生成時往往需要進行分組聚集運算,如果在資料庫中先進行一次分組聚集,能夠大大減少取到報表伺服器的記錄數,加快取數和報表運算的速度。看如下報表 這是乙個典型的交叉分組報表,其sql有兩種寫法 第一種 select 產品,客戶,銷量 from 購買記錄表 第二種 select...

關於MongoDB的group分組

關於mongodb的group分組 測試條件 windows mongodb 1.8.2 先插入測試資料 for var i 1 i 20 i 1.普通 分組查詢 db.test.group initial reduce function doc,prev db.runcommand initial...