SQL之美第七篇:SQL巧解逻辑题
近日,看到大佬发了个逻辑题:

这里的核心就在于如何将这三句话转换成SQL条件。
想挑战下的可以自行写SQL实现,欢迎投稿新的SQL给我,共同学习哈!
以下是另一位大佬的SQL答案:
with v1 as
(
select 3 m,5 n from dual
union all select 3 m,6 n from dual
union all select 3 m,8 n from dual --
union all select 4 m,2 n from dual
union all select 4 m,5 n from dual
union all select 4 m,6 n from dual
union all select 5 m,1 n from dual
union all select 5 m,5 n from dual
union all select 5 m,7 n from dual--
union all select 6 m,1 n from dual
union all select 6 m,2 n from dual
)
,g1 as
(select * from v1
where not exists (select 1 from v1 v2 where v2.m=v1.m and (select count(*) from v1 v3 where v3.n=v2.n)=1))
,g2 as
(select * from g1 where (select count(*) from g1 g12 where g12.n=g1.n)=1)
,g3 as (
select * from g2 where (select count(*)from g2 g22 where g22.m=g2.m)=1)
select * from g3
感兴趣可以不看解析自行理解。反正我是花了20分钟才彻底看懂题目+SQL 哈哈。
简要解析:
V1 :创造数据
G1 :A不知道且知道B肯定不知道,SQL取反向 这里直接将满足 A知道且B肯定知道的数据排除,3和5开头的消除
G2:B不知道后知道,SQL取正向,在G1的结果集基础上 拿到个位号不重复的结果集
G3: A也知道,SQL取正向,在G2的结果集基础上, 拿到十位数不重复的最终结果
本人逻辑理解:
第一句话:如果给B的是8或7,B一定知道是38或57。因为8和7是唯一的不重复的。同时A确认B不知道结果,所以A一定不是3或8,
排除后剩余:42 45 46 61 62
原因:如果是4或2。B就有可能拿到8或7,A就无法肯定B不知道。
第二句话: B说他知道了
排除后剩余:45,46 ,61,
原因:如果B拿到了2,他分不清是42还是62。
第三句话 a说他也知道了
答案一定是61,
原因:如果他拿到了4,就分不清是45还是46。
优美的SQL总是如此令人着迷!
微信扫一扫
关注该公众号




