程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 數據庫知識 >> 其他數據庫知識 >> MSSQL >> SQL中Group分組獲得Top N辦法完成可首選row_number

SQL中Group分組獲得Top N辦法完成可首選row_number

編輯:MSSQL

SQL中Group分組獲得Top N辦法完成可首選row_number。本站提示廣大學習愛好者:(SQL中Group分組獲得Top N辦法完成可首選row_number)文章只能為提供參考,不一定能成為您想要的結果。以下是SQL中Group分組獲得Top N辦法完成可首選row_number正文


有產物表,包括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 KEY CLUSTERED
(
[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< 11 order by city asc,addtime desc

2、采取cross apply辦法,履行了3次,根本都在3分5秒以上,曾經很慢了。

select distinct b.id,b.name,b.city from products a
cross apply (select top 10 * 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) < 10
order 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 for
select 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 top 10 id,name,city,addtime from products where city = @city
fetch next from mycursor into @city
end
close mycursor
deallocate mycursor
Select * from #Top order by city asc,addtime desc
drop table #Top

經由過程上述比較不難發明,在面對Group獲得Top N場景時,可以首選row_number,游標cursor其次,別的兩個就根本不斟酌了,數據量年夜的時刻基本沒法應用。
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved