MSSQL使用窗口函数查询去重数据

USE ReportServer
GO

--DROP TABLE TB_Books

 

 1.创建表

1 CREATE TABLE TB_Books
2 (
3     FID INT IDENTITY(1,1) PRIMARY KEY
4     ,FName NVARCHAR(400) NOT NULL
5     ,FCategory NVARCHAR(40) NOT NULL
6     ,FCreateDate DATETIME NOT NULL
7 )

 

2. 创建初始化数据

 1 INSERT TB_Books
 2 VALUES
 3 ('AAA','bbb','2020-01-11')
 4 ,('flask','python','2020-02-11')
 5 ,('pandas','python','2020-03-11')
 6 ,('numpy','python','2020-02-21')
 7 ,('ASP.NET Core','.net','2020-02-01')
 8 ,('ASP.NET','.net','2010-02-11')
 9 ,('WPF','.net','2020-12-11')
10 ,('MSSQL','db','2020-5-11')
11 ,('MYSQL','db','2020-6-11')
12 ,('MONGODB','db','2020-07-11')

 

3. 查询表数据

1 SELECT * FROM TB_Books;

显示结果:

 

 4. 使用窗口函数分组,并取分组中第一条数据

 1 WITH T AS
 2 (
 3   SELECT 
 4     ROW_NUMBER() OVER(PARTITION BY FCategory ORDER BY FCreateDate DESC) AS A,
 5     ROW_NUMBER() OVER( ORDER BY FCreateDate DESC) AS B,
 6     TB.*
 7   FROM TB_Books AS TB
 8 )
 9 SELECT
10 
11   FName, A, B
12 
13 FROM T 
14   WHERE 
15   A=1 -- 按FCategory分组数据中,取第一条数据
16 -- AND
17 --  T.B BETWEEN 1 AND 20;

显示结果:

 

posted @ 2020-10-27 11:58  小站记忆  阅读(961)  评论(0编辑  收藏  举报