zoukankan      html  css  js  c++  java
  • SqlServer2005中使用row_number()在一个查询中删除重复记录

           在SqlServer2005中,提供了一个row_number()的函数,我们经常用它做DataBase数据分页.
    下面我们来看下,如何利用它来删除一个表中重复记录:

    If Exists(Select * From tempdb.Information_Schema.Tables Where Table_Name Like '#Temp%')
        Drop Table #temp
     
    Create Table #temp ([Id] int, [Name] varchar(50), [Age] int, [Sex] bit default 1)
    Go
     
    Insert Into #temp ([Id] , [Name] , [Age] , [Sex] ) Values(1,'James',25,default)
    Insert Into #temp ([Id] , [Name] , [Age] , [Sex] ) Values(1,'James',25,default)
    Insert Into #temp ([Id] , [Name] , [Age] , [Sex] ) Values(1,'James',25,default)
     
    Insert Into #temp ([Id] , [Name] , [Age] , [Sex] ) Values(2,'Lisa',24,0)
    Insert Into #temp ([Id] , [Name] , [Age] , [Sex] ) Values(2,'Lisa',24,0)
    Insert Into #temp ([Id] , [Name] , [Age] , [Sex] ) Values(2,'Lisa',24,0)
     
    Insert Into #temp ([Id] , [Name] , [Age] , [Sex] ) Values(3,'Mirsa',23,0)
    Insert Into #temp ([Id] , [Name] , [Age] , [Sex] ) Values(3,'Mirsa',23,0)
    Insert Into #temp ([Id] , [Name] , [Age] , [Sex] ) Values(3,'Mirsa',23,0)
     
    Insert Into #temp ([Id] , [Name] , [Age] , [Sex] ) Values(4,'John',26,default)
    Insert Into #temp ([Id] , [Name] , [Age] , [Sex] ) Values(5,'Abraham',28,default)
    Insert Into #temp ([Id] , [Name] , [Age] , [Sex] ) Values(6,'Lincoln',30,default)
     
     
    Delete T From
    (Select Row_Number() Over(Partition By [ID],[Name],[Age],[Sex] order By [ID]) As RowNumber,* From #Temp)T
    Where T.RowNumber > 1
     
     
    Select * From #temp
     
    注意倒数第二句脚本,我们在一个查询实现这个功能.
    你可以自己执行T-SQL script 看效果.希望对您开发有帮助!
     


    作者:Petter Liu
    出处:http://www.cnblogs.com/wintersun/
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
    该文章也同时发布在我的独立博客中-Petter Liu Blog

  • 相关阅读:
    汉文博士 0.5.6.2345 修订版发布
    汉文博士 0.5.6 正式版发布
    汉文博士 0.5.5 正式版发布
    汉文博士新测试版发布(0.5.4.2228)
    海盗(Haidao)网店系统最新官方版
    ZipMarket数字内容/素材交易网站源码项目
    windows phone 8 使用页面传对象的方式 实现页面间的多值传递
    仿win8磁贴界面以及功能
    三角形状的点阵模糊效果iOS源码
    Coding iOS客户端应用源码
  • 原文地址:https://www.cnblogs.com/wintersun/p/1824161.html
Copyright © 2011-2022 走看看