如何利用SQL进行推理
程序员文章站
2022-11-20 12:58:46
数据库环境:sql server 2008r2
有如下需求:
baker, cooper, fletcher, miller and smith住在一座房子的不同楼层。...
数据库环境:sql server 2008r2
有如下需求:
baker, cooper, fletcher, miller and smith住在一座房子的不同楼层。
baker 不住顶层。cooper不住底层。
fletcher 既不住顶层也不住底层。miller住得比cooper高。
smith住的楼层和fletcher不相邻。
fletcher住的楼层和cooper不相邻。
用sql写出来
解题思路:
先实现所有人住楼层的排列组合,然后把条件套进去即求得。如何实现排列组合,
1.基础数据准备
--准备基础数据,用a、b、c、d、e分别表示baker, cooper, fletcher, miller and smith
create table ttb ( subname varchar(1) , realname varchar(10) ) insert into ttb values ( 'a', 'baker' ), ( 'b', 'cooper' ), ( 'c', 'fletcher' ), ( 'd', 'miller' ), ( 'e', 'smith' )
2.生成所有可能情况的排列组合
--生成a、b、c、d、e所有的排列组合
with x0 as ( select convert(varchar(10), 'a') as hid union all select convert(varchar(10), 'b') as hid union all select convert(varchar(10), 'c') as hid union all select convert(varchar(10), 'd') as hid union all select convert(varchar(10), 'e') as hid ), x1 as ( select hid from x0 where len(hid) <= 5 union all select convert(varchar(10), a.hid + b.hid) as hid from x0 a inner join x1 b on charindex(a.hid, b.hid, 1) = 0 ) select hid as name into #tt from x1 where len(hid) = 5 order by hid
3.加入条件,找出满足要求的楼层安排
with x2 as ( select name from #tt where substring(name, 5, 1) <> 'a'--baker 不住顶层 and substring(name, 1, 1) <> 'b'--cooper不住底层 and ( substring(name, 1, 1) <> 'c' and substring(name, 5, 1) <> 'c'--fletcher 既不住顶层也不住底层 ) and name like '%b%d%'--miller住得比cooper高 and name not like '%ce%' and name not like '%ec%' --smith住的楼层和fletcher不相邻 and name not like '%bc%' and name not like '%cb%' --fletcher住的楼层和cooper不相邻 ), x3--生成楼层号 as ( select number as id , substring(x2.name, number, 1) as name from master.dbo.spt_values inner join x2 on 1 = 1 where type = 'p' and number <= 5 and number >= 1 ) select a.id as 楼层, b.realname as 姓名 from x3 a inner join ttb b on b.subname = a.name order by id
楼层安排如下:
通过以上的代码的介绍,希望对大家的学习有所帮助。