• 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;

    显示结果:

  • 相关阅读:
    Aptana 由于没有关闭编辑器而导致的启动不起来了。
    postgresql备份导入数据库小记
    [转] js 事件冒泡 阻止
    ruby 取得ip
    [ 转 ] 网页聊天室的原理
    ryby 数组笔记
    第一个rails应用
    vue-router-5-命名路由
    vue-router-4-编程式导航
    vue-router-3-嵌套路由
  • 原文地址:https://www.cnblogs.com/shouwu/p/13884027.html
Copyright © 2020-2023  润新知