haiwer yangID:Haiwer
6281次访问,排名15428(-14)好友138人,关注者158
您可以用一些词来描述自己,如行业,爱好,职业,学校,公司等
Haiwer的文章
原创 13 篇
翻译 0 篇
转载 1 篇
评论 56 篇
最近评论
ycj840212:顶一下.
bbqbin:顶了,收藏了
dengqiong080704:蛮好的,学习下
axer21:mark
ybb1981:强.. 学习.. 收藏
文章分类
收藏
    相册
    存档
    软件项目交易
    订阅我的博客
    XML聚合  FeedSky
    订阅到鲜果
    订阅到Google
    订阅到抓虾
    订阅到BlogLines
    订阅到Yahoo
    订阅到GouGou
    订阅到飞鸽
    订阅到Rojo
    订阅到newsgator
    订阅到netvibes

    原创 又见火车票问题收藏

    新一篇: 一个用于跟踪和发现程序错误的触发器 | 旧一篇: 保持两表数据一致的触发器事例

    不过这次的火车票问题其实并不是火车票问题,而是取最大植的问题 。

    问题描述:

    比如说从广州到北京 有四个站
    站号   价格    站名
    1       0       广州
    2       50       长沙
    3       30       武汉
    4       220      北京
    第一个站是起点站,所以第一个站是0元,从第一个到第二个站是50元,第二到第三是30元 等等
    现在问题在这里,看你现在有多少钱在身上(该金额由用户输入,比如249),从某一站出发(该站名也由用户输入,比如长沙),求最远能到达哪个站?
    用一条SQL语句,不使用存储过程实现。

    问题分析:

    可能有两个方向都可以走,所以必须考虑两个方向的问题。

    对于远没有明确定义,可以是价格高的为远,也可以认为站数 多的为远

    语句:

    1、如果价格高的为远
    --测试环境
    declare @Test table (站号 int, 价格 int, 站名 varchar(4))
    insert @Test
    select 1, 0, '广州' union all
    select 2, 50, '长沙' union all
    select 3, 30, '武汉' union all
    select 4, 220, '北京'

    --语句
    select top 1 * from (      --选择第一个
    select 站号,站名,(select sum(价格) from @test where 站号<=b.站号 and 站号>(select 站号 from @test where 站名='长沙')) as 价格
    from @test b         --正向
    union all
    select 站号,站名,(select sum(价格) from @test where 站号>b.站号 and 站号<=(select 站号 from @test where 站名='长沙')) as 价格
    from @test b       --反向
    ) as t
    where 价格<=249         --限制价格
    order by 价格 desc     --价格高的为远,选择价格最高的

    --结果
    站号          站名   价格         
    ----------- ---- -----------
    1           广州   50

    (所影响的行数为 1 行)

    2、如果站数多的为远
    --测试环境
    declare @Test table (站号 int, 价格 int, 站名 varchar(4))
    insert @Test
    select 1, 0, '广州' union all
    select 2, 50, '长沙' union all
    select 3, 30, '武汉' union all
    select 4, 220, '北京'

    --语句
    select top 1 * from (      --选择第一个
    select 站号,站名,(select sum(价格) from @test where 站号<=b.站号 and 站号>(select 站号 from @test where 站名='长沙')) as 价格
    ,abs(站号-(select 站号 from @test where 站名='长沙')) as 站数
    from @test b      --正向
    union all
    select 站号,站名,(select sum(价格) from @test where 站号>b.站号 and 站号<=(select 站号 from @test where 站名='长沙')) as 价格
    ,abs(站号-(select 站号 from @test where 站名='长沙')) as 站数
    from @test b       --反向
    ) as t
    where 价格<=249    --限制价格
    order by 站数 desc,价格 desc     --站数多的为远,选择站数最多的,一样多的选择价格高的

    --结果
    站号          站名   价格          站数         
    ----------- ---- ----------- -----------
    1           广州   50          1

    (所影响的行数为 1 行)

     

     

    发表于 @ 2007年08月11日 15:25:00|评论(loading...)|编辑

    新一篇: 一个用于跟踪和发现程序错误的触发器 | 旧一篇: 保持两表数据一致的触发器事例

    评论:没有评论。

    发表评论  


    当前用户设置只有注册用户才能发表评论。如果你没有登录,请点击登录
    Csdn Blog version 3.1a
    Copyright © Haiwer