灰铁

来源:互联网 发布:淘宝人气宝推广在哪 编辑:程序博客网 时间:2024/04/19 20:28

 

问题:

有如下记录:

ID      sub_id  结论    编号    类型
CP001      29    不合格  BH002    1
CP001    23    不合格  BH005    2
CP001    25    合格    BH006    1
CP002    28    不合格  BH007    1
CP002    32    合格    BH001    1
............................................

现在要检索满足如下要求的记录:

同一个ID下,最大的sub_id 对应的结论为 不合格,但同时满足 最小的sub_id 对应的结论为 合格,并且类型均为1。
结果应该如下:

ID      sub_id  结论    编号    类型
CP001      29    不合格  BH002    1

当然直接显示一个ID 也是可以的。


大家说这个SQL 语句最简单的实现该怎么写呢?

 

我的解决:

(
select ID, max(sub_id) as sub_id,type,con
from code
where con='不合格' and type=1
group by  ID,type,con
)
union
(
select ID, min(sub_id) as sub_id,type,con
from code
where  con='合格' and type=1
group by  ID,type,con
)
union
(
select *
from code c
where ID=c.ID
and sub_id not in (select max(sub_id) as sub_id from code group by ID)
and sub_id not in (select min(sub_id) as sub_id from code group by ID)
)

--完全集合论
--如果符合条件的最大和最小年龄相等时,他们会同时出现!
(有且仅有存在符合所有条件,年龄和类型相同,结论不同的两个实体)