不过这次的火车票问题其实并不是火车票问题,而是取最大植的问题 。
问题描述:
比如说从广州到北京 有四个站
站号 价格 站名
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 行)