SQL Server 2008 R2——分組取前幾名

版權聲明:本文爲博主原創文章 未經許可不得轉載  
html

請經過右側公告中的「聯繫郵箱(wlsandwho@foxmail.com)」聯繫我spa

未經做者受權勿用於學術性引用。code

未經做者受權勿用於商業出版、商業印刷、商業引用以及其餘商業用途。                   htm

 

本文不按期修正完善,爲保證內容正確,建議移步原文處閱讀。                                                               <--------總有一天我要本身作一個模板幹掉這隻土豆blog

本文連接:http://www.cnblogs.com/wlsandwho/p/4829125.htmlget

恥辱牆:http://www.cnblogs.com/wlsandwho/p/4206472.htmlit

=======================================================================模板

只是寫個簡單的例子,不要在乎星號什麼的。class

複製代碼
 1 USE tempdb
 2 
 3 IF EXISTS(SELECT * FROM sysobjects WHERE id=OBJECT_ID(N't_Test') AND OBJECTPROPERTY(id,N'IsUserTable')=1)
 4 DROP TABLE t_Test
 5 GO
 6 CREATE TABLE t_Test(
 7 OnLineDate    DATETIME,
 8 ProductID    NVARCHAR(8),
 9 WebPage        NVARCHAR(32)
10 )
11 GO
12 INSERT INTO t_Test VALUES(GETDATE(),'11111111','1cccccccccc')
13 WAITFOR DELAY '00:00:01'
14 INSERT INTO t_Test VALUES(GETDATE(),'11111111','1eeeeeeeeee')
15 WAITFOR DELAY '00:00:01'
16 INSERT INTO t_Test VALUES(GETDATE(),'11111111','1bbbbbbbbbb')
17 WAITFOR DELAY '00:00:01'
18 INSERT INTO t_Test VALUES(GETDATE(),'11111111','1dddddddddd')
19 WAITFOR DELAY '00:00:01'
20 INSERT INTO t_Test VALUES(GETDATE(),'11111111','1aaaaaaaaaa')
21 WAITFOR DELAY '00:00:01'
22 INSERT INTO t_Test VALUES(GETDATE(),'22222222','2aaaaaaaaaa')
23 WAITFOR DELAY '00:00:01'
24 INSERT INTO t_Test VALUES(GETDATE(),'22222222','2cccccccccc')
25 WAITFOR DELAY '00:00:01'
26 INSERT INTO t_Test VALUES(GETDATE(),'22222222','2eeeeeeeeee')
27 WAITFOR DELAY '00:00:01'
28 INSERT INTO t_Test VALUES(GETDATE(),'22222222','2dddddddddd')
29 WAITFOR DELAY '00:00:01'
30 INSERT INTO t_Test VALUES(GETDATE(),'22222222','2bbbbbbbbbb')
31 GO
32 
33 SELECT OnLineDate,ProductID,WebPage,ROW_NUMBER() OVER(PARTITION BY ProductID ORDER BY OnLineDate DESC) AS rowRum FROM t_Test 
34 GO
35 -----------------------------
36 WITH t_Temp
37 AS
38 (
39 SELECT OnLineDate,ProductID,WebPage,ROW_NUMBER() OVER(PARTITION BY ProductID ORDER BY OnLineDate DESC) AS rowRum FROM t_Test 
40 )
41 SELECT * FROM t_Temp
42 WHERE t_Temp.rowRum<=3
43 GO
44 -----------------------------
45 WITH t_Temp
46 AS
47 (
48 SELECT OnLineDate,ProductID,WebPage,ROW_NUMBER() OVER(PARTITION BY ProductID ORDER BY OnLineDate DESC) AS rowRum FROM t_Test 
49 )
50 SELECT * FROM t_Temp
51 WHERE t_Temp.rowRum<=3 ORDER BY ProductID ASC,OnLineDate DESC
52 GO
複製代碼

=======================================================================object

最近沒什麼好寫的,QQ羣裏有人問問題,就隨手寫了一個。

然而那人拿了以後就再也沒有反應/反饋了。

因此只能對廣大伸手黨說一句,我真心但願大家都能看看《你的知識須要管理 田志剛》這本書。

相關文章
相關標籤/搜索