zoukankan      html  css  js  c++  java
  • 关于ROW_NUMBER函数的使用(The use of ROW_NUMBER function )

    1、用于删除重复记录(The use of to delete the common record)

    例子:(Example)

    #1初始化数据(Initialize the data)

    CREATE TABLE #tmp1 ( id int, name nvarchar(20), age int );

    INSERT INTO #tmp1 VALUES(1,'CangoWu',25)

    INSERT INTO #tmp1 VALUES(2,'CangoWu',25)

    INSERT INTO #tmp1 VALUES(3,'CangoWu',25)

    INSERT INTO #tmp1 VALUES(4,'Ajay',29)

    INSERT INTO #tmp1 VALUES(5,'Ajay',29)

    INSERT INTO #tmp1 VALUES(6,'Ajay',29)

     #2操作SQL(T-SQL)

    --操作前(Before the operation)

    SELECT * FROM #tmp1

    id name age
    1 CangoWu 25
    2 CangoWu 25
    3 CangoWu 25
    4 Ajay 29
    5 Ajay 29
    6 Ajay 29

    --操作后(After the operation)

    SELECT name,age FROM
    (
    SELECT *,ROW_NUMBER() OVER(PARTITION BY name ORDER BY id) row FROM #tmp1
    )tmp
    WHERE row = 1

    name age
    Ajay 29
    CangoWu 25

    2、记录相同字段不重复显示(The record fields repeat same display)

    例子:(Example)

    #1初始化数据(Initialize the data)

    CREATE TABLE #tmp2 ( id int, name nvarchar(20), age int, month int, salary int );

    INSERT INTO #tmp2 VALUES(1,'CangoWu',25,1,2500)

    INSERT INTO #tmp2 VALUES(2,'CangoWu',25,2,2500)

    INSERT INTO #tmp2 VALUES(3,'CangoWu',25,3,2500)

    INSERT INTO #tmp2 VALUES(4,'CangoWu',25,4,2500)

    INSERT INTO #tmp2 VALUES(5,'CangoWu',25,5,2500)

    INSERT INTO #tmp2 VALUES(6,'CangoWu',25,6,2500)

    INSERT INTO #tmp2 VALUES(11,'Preston',35,1,8000)

    INSERT INTO #tmp2 VALUES(12,'Preston',35,2,8000)

    INSERT INTO #tmp2 VALUES(13,'Preston',35,3,8000)

    INSERT INTO #tmp2 VALUES(14,'Preston',35,4,8000)

    INSERT INTO #tmp2 VALUES(15,'Preston',35,5,8000)

    INSERT INTO #tmp2 VALUES(16,'Preston',35,6,8000)

    INSERT INTO #tmp2 VALUES(21,'Ajay',29,1,5000)

    INSERT INTO #tmp2 VALUES(22,'Ajay',29,2,5000)

    INSERT INTO #tmp2 VALUES(23,'Ajay',29,3,5000)

    INSERT INTO #tmp2 VALUES(24,'Ajay',29,4,5000)

    INSERT INTO #tmp2 VALUES(25,'Ajay',29,5,5000)

    INSERT INTO #tmp2 VALUES(26,'Ajay',29,6,5000)

     #2操作SQL(T-SQL)

    SELECT
    name = (CASE WHEN row = 1 THEN name ELSE '' END)
    ,age = (CASE WHEN row = 1 THEN age ELSE NULL END)
    ,month
    ,salary
    FROM
    (
    SELECT *,ROW_NUMBER() OVER(PARTITION BY name ORDER BY id) row FROM #tmp2
    )tmp

    name age month salary
    Ajay 29 1 5000
         2 5000
         3 5000
         4 5000
         5 5000
         6 5000
    CangoWu 25 1 2500
         2 2500
         3 2500
         4 2500
         5 2500
         6 2500
    Preston 35 1 8000
         2 8000
         3 8000
         4 8000
         5 8000
         6 8000

  • 相关阅读:
    浅谈求卡特兰数的几种方法
    WPF基础知识、界面布局及控件Binding
    .net平台下C#socket通信(上)
    .net泛型理解
    面向过程和面向对象及面向对象的三大特征
    C#配置文件管理
    MOGRE学习笔记(3)--MOGRE小项目练习
    委托、事件学习笔记
    MOGRE学习笔记(2)
    MOGRE学习笔记(1)
  • 原文地址:https://www.cnblogs.com/cangowu/p/3985963.html
Copyright © 2011-2022 走看看