ITPub 上的一道题,学习下思路

有意思的,从别处看来的即可为己用--拿来主义

数据库:MS SQL 2000:

drop table mytest
go

create table mytest
(
  sn      int,
  code    varchar(8),
  ins_no  varchar(6),
)
go

insert mytest values(1, '01', 'A')
insert mytest values(1, '01', 'B')
insert mytest values(2, '02', 'A')
insert mytest values(2, '02', 'D')
insert mytest values(3, '01', 'A')
insert mytest values(3, '01', 'B')
insert mytest values(4, '03', 'A')
insert mytest values(4, '03', 'B')
insert mytest values(4, '03', 'C')
insert mytest values(5, '03', 'B')
insert mytest values(5, '03', 'C')
insert mytest values(6, '02', 'A')
insert mytest values(6, '02', 'C')
insert mytest values(6, '02', 'D')
go

select * from mytest
go

sn   code      ins_no
---  --------  ------
1    01        A
1    01        B
2    02        A
2    02        D
4    03        A
4    03        B
4    03        C
5    03        B
5    03        C
6    02        A
6    02        C

6    02        D

需求: 依据题意,应该是对于不同的 sn 若 code,ins_no 这两列 的值是 (完全)相等的,那么就只显示一个 sn,code,ins_no, 如: sn=1 跟 sn=3 的情况。

字段SN是用来分组的。如果不同SN下的记录完全一样(除了SN本身),包括记录条数、字段内容,则我希望只保留一个分组,例子中分组1和3满足这种情况,所以把分组3剔除掉。
但分组2和分组6由于记录条数不等,所以仍然保留。

思路即为: 

新增一个 字段 count_num 用来做是否完全匹配的判断


看到一位 大虾写的:

select min(a.sn) as sn,a.code,a.ins_no
from mytest a inner join (select sn,count(1) as count_num from mytest b group by sn) b
on a.sn=b.sn
group by a.code,a.ins_no,b.count_num
order by sn

另一位大虾写的(不明觉厉)

使用相关子查询:

select * from mytest where
sn = (
select distinct sn from sn t1  -->这里开始分组比较
where not exists(
select distinct sn from mytest t2 -->取另一组
where t2.sn<t1.sn                -->相同时取最小编号
and 
exists(                             -->组比较
select code, ins_no from mytest t3
where sn=t1.sn
minus 
select code, ins_no from mytest t4
where sn=t2.sn)))

有空再深入研究。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值