• SQL删除重复数据 Yang


    记录一下!

    CREATE TABLE DuplicateTable
    (
       ID INT IDENTITY(1,1) PRIMARY KEY,
       USERNAME NVARCHAR(20),    
       AGE INT,
       PROVINCE NVARCHAR(20),
       CITY NVARCHAR(20),
       ToTALGrades DECIMAL(18,2)
    )
    INSERT INTO DuplicateTable(USERNAME,AGE,PROVINCE,CITY,ToTALGrades)
    VALUES('Yangzhi',23,'四川','成都',600.5);
    INSERT INTO DuplicateTable(USERNAME,AGE,PROVINCE,CITY,ToTALGrades)
    VALUES('Yangzhi',23,'四川','汶川',600.5);
    INSERT INTO DuplicateTable(USERNAME,AGE,PROVINCE,CITY,ToTALGrades)
    VALUES('Yangzhi',23,'四川','成都',605);
    INSERT INTO DuplicateTable(USERNAME,AGE,PROVINCE,CITY,ToTALGrades)
    VALUES('Yangzhi',21,'四川','成都',600.5);
    INSERT INTO DuplicateTable(USERNAME,AGE,PROVINCE,CITY,ToTALGrades)
    VALUES('Zhangsan',24,'重庆','重庆',559);
    INSERT INTO DuplicateTable(USERNAME,AGE,PROVINCE,CITY,ToTALGrades)
    VALUES('Zhangsan',24,'重庆','重庆',559);
    INSERT INTO DuplicateTable(USERNAME,AGE,PROVINCE,CITY,ToTALGrades)
    VALUES('Lisi',22,'重庆','重庆',559);
    INSERT INTO DuplicateTable(USERNAME,AGE,PROVINCE,CITY,ToTALGrades)
    VALUES('Lisi',22,'重庆','重庆',559);
    INSERT INTO DuplicateTable(USERNAME,AGE,PROVINCE,CITY,ToTALGrades)
    VALUES('Wangwu',22,'重庆','重庆',595);
    INSERT INTO DuplicateTable(USERNAME,AGE,PROVINCE,CITY,ToTALGrades)
    VALUES('Wangwu',23,'重庆','重庆',595);
    INSERT INTO DuplicateTable(USERNAME,AGE,PROVINCE,CITY,ToTALGrades)
    VALUES('Lisi',23,'重庆','重庆',600.2);
    INSERT INTO DuplicateTable(USERNAME,AGE,PROVINCE,CITY,ToTALGrades)
    VALUES('Wangwu',23,'重庆','重庆',595);
    
    
    SELECT * FROM DuplicateTable dt
    
    DECLARE
        @sql NVARCHAR(4000),
        @groupByConditions NVARCHAR(800)
    SELECT @groupByConditions=ISNULL(@groupByConditions+',','')+ col.name FROM ( SELECT s.name FROM syscolumns s WHERE id=OBJECT_ID(N'DuplicateTable') AND s.name<>'ID')col
    SET @sql='SELECT MIN(ID) ID  FROM DuplicateTable dt GROUP BY '+@groupByConditions+' ORDER BY ID ASC'
    SET @sql= 'DELETE * FROM DuplicateTable dt WHERE dt.ID NOT IN('+@sql+')'
    EXEC(@sql)
    
    
    
    --查询一个数据库有那些数据表
    SELECT * FROM sysobjects s WHERE s.xtype='U'
    
    --查询一个表有那些列
    SELECT s.name FROM syscolumns s WHERE id=OBJECT_ID(N'DuplicateTable') AND s.name<>'ID'
  • 相关阅读:
    POJ 2255. Tree Recovery
    Ural 1011. Conductors
    Ural 1010. Discrete Function
    算法导论学习 之 解递归式
    算法导论学习 之 渐进符号
    kubernetes-集群构建
    kubernetes-集群备份和恢复
    kubernetes-概念
    Kubernetes-常用命令
    kubernetes-单机实验(入门)
  • 原文地址:https://www.cnblogs.com/Yang2012/p/2935164.html
Copyright © 2020-2023  润新知