sql 查询重复记录

php中文网
发布: 2016-06-07 17:47:48
原创
1215人浏览过

本文章讲了三款sql 查询重复记录与删除重复记录的sql语句,并且每个都利用了不同的方法来举例说明其它作用与可行性,以及它的效率。

本文章讲了三款sql 查询重复记录与删除重复记录的sql语句,并且每个都利用了不同的方法来举例说明其它作用与可行性,以及它的效率。

select *, count(distinct name) from table group by name

结果:

id name count(distinct name)
1 a 1
2 b 1
3 c 1

方法二
表 table1
id regname postionsn personsn
1 山东齐鲁制药 223 2
2 山东齐鲁制药 224 2
3 北京城建公司 225 2
4 科技公司 225 2

我想获得结果是

id regname postionsn personsn
1 山东齐鲁制药 223 2
3 北京城建公司 225 2
4 科技公司 225 2

select distinct regname,postionsn,personsn from table1

如果查询的是多列 distinct 用和不用一样

标书对比王
标书对比王

标书对比王是一款标书查重工具,支持多份投标文件两两相互比对,重复内容高亮标记,可快速定位重复内容原文所在位置,并可导出比对报告。

标书对比王 215
查看详情 标书对比王

只能用group by

用group by regname
select * from table1 where id in (select min(id) from table1 group by regname) and personsn=2


实例三

个人成绩表:
学号  课号   成绩
01   01    80
01   02    79
01   03    88
02   01    87
02   02    77
02   03    68

用sql把上表转换为:
学号  课号01  课号02  课号03
01   80     79    88
02   87     77    68

---------建表----------
create table tab_score
(
    bid int identity(0,1) primary key ,--流水号
    sid varchar(20) not null,--学生号
    cid varchar(20) not null,--课程号
    score int--成绩
)
insert into tab_score select's01','c01','90' union all select 's01','c02','92' union all select 's01','c03','93'
                  union all select 's02','c01','81' union all select 's02','c02','82'

/*---固定列的写法,后面的写法将是根据有几个课程id来动态组装中间的sum语句,然后加上头尾就成了,
理解了这种'静态'写法,剩下的只是'动态'组装中间sum语句的工作----*/

select * from tab_score
select sid,sum(case cid when 'c01' then score else '0' end) as 'c01',
       sum(case cid when 'c02' then score else '0' end) as 'c02',
           sum(case cid when 'c03' then score else '0' end) as 'c03'          
  from tab_score group by sid         


-----'动态'列的写法,定义一个变量来组装中间的sum语句,其中用到子查询表(原来不用这方法一直会出现重复列)-------   

declare @s varchar(1000)
set @s=''
select  @s=@s+', sum(case cid when '+''''+ a.cid+''''+' then score else ''0'' end) as '+''''+a.cid+'''' 
  from ( select distinct cid from tab_score) a
print @*
**ec('select sid'+@s+'from tab_score group by sid')
最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号