当前位置: 代码网 > it编程>数据库>MsSqlserver > 如何利用SQL进行推理

如何利用SQL进行推理

2024年05月18日 MsSqlserver 我要评论
数据库环境:sql server 2008r2有如下需求:baker, cooper, fletcher, miller and smith住在一座房子的不同楼层。baker 不住顶层。cooper不

数据库环境: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

楼层安排如下:

通过以上的代码的介绍,希望对大家的学习有所帮助。

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com