查询2列编号的数据

时间:2011-05-03 14:06:14

标签: sql-server

我有这个问题,我似乎无法理解......基本上我有一个用户输入的表单

  • 开始一英里
  • 开始院子
  • end mile
  • end yard

我正在尝试使用用户输入的值查询我的SQL Server数据库...我可以检索信息,但我只需要查询帮助。

问题是数据在数据库中采用以下格式:

 ID | mile | yard | gps lat | gps long | rotten | split | wheel_cut | broken | quality |
  1, 234, 2342,   35.23143, -123.32423, 1, 2, 1, 2, 2 
  2, 234, 2954,   35.23143, -123.32423, 1, 2, 1, 2, 2 
  3, 234, 2994,   35.23143, -123.32423, 1, 2, 1, 2, 2 
  4, 235,   42,   35.23143, -123.32423, 1, 2, 1, 2, 2 
  5, 235, 2842,   35.23143, -123.32423, 1, 2, 1, 2, 2 
  6, 236,  242,   35.23143, -123.32423, 1, 2, 1, 2, 2 
  7, 236, 2342,   35.23143, -123.32423, 1, 2, 1, 2, 2 
  8, 237,  282,   35.23143, -123.32423, 1, 2, 1, 2, 2 
  9, 238, 2342,   35.23143, -123.32423, 1, 2, 1, 2, 2 
 10, 238, 4342,   35.23143, -123.32423, 1, 2, 1, 2, 2 
 11, 239,  742,   35.23143, -123.32423, 1, 2, 1, 2, 2 

我需要同时查询英里和码数,例如用户键入:

  • start mile = 234
  • start yard = 2954

  • end mile = 236

  • end yard = 2342

查询应输出ID 3,4,5,6和7.

如果我只是查询WHERE mile > 234 AND yard > 2954. ..它将忽略ID 4,因为码数小于2954。

SELECT   
    id, mile,  yard, gps_lat, gps_long, rotten, split, wheel_cut, broken, quality
FROM    
    database
WHERE 
    gps_lat IS NOT NULL 
    AND (???????)
ORDER BY 
    mile, yard.

有没有人可以帮我解决这个问题?任何建议都会受到欢迎!

我希望我能够清楚地解释这个情况......

干杯,

尼尔

4 个答案:

答案 0 :(得分:3)

我认为问题是由两列不同格式的两列存储距离引起的。

您可以将里程存储为小数并删除码数吗?

如果没有,如果您将Mile and Yard列转换为Feet会怎么样?

select *
  from YourTable
 where ((Mile * 5280) + (Yard * 3)) 
  between ((StartMile * 5280) + (StartYard +3))
      and ((StopMile * 5280) + (StopYard * 3))

答案 1 :(得分:1)

这不是最好的方法,但您可以尝试将英里数据点转换为码数,然后添加两个数据点,然后在开始和停止码数之间进行选择。

所以例如:

declare @startmile int, @endmile int, @startyard int, @endyard int

set @startyard=@startyard+(@startmile*1760)
set @endyard=@endyard+(@endmile*1760)


select *
from dbo.Table_1
where yard+(mile*1760) between @startyard and @endyard

可能有更好的方式来写这个,但我想不出来。

答案 2 :(得分:1)

感谢所有回复的人!最后我最终使用了以下内容...... Cheers Neil

--set values
declare @startmile_int AS int
declare @endmile_int AS int
declare @startyard_int AS int 
declare @endyard_int AS int
declare @startyard AS int
declare @endyard AS int

SET @startmile_int=529 
SET @endmile_int=535
SET @startyard_int=34 
SET @endyard_int=406

--turn miles into yards
set @startyard=@startyard_int+(@startmile_int*1760)
set @endyard=@endyard_int+(@endmile_int*1760)

SELECT   id, mile,yard, gps_lat, gps_long, rotten, split, wheel_cut, broken, quality
FROM         database WHERE gps_lat IS NOT NULL AND yard+(mile*1760) between @startyard and @endyard ORDER BY mile, yard

答案 3 :(得分:0)

如果我们避免进行计算,那么优化器可以使用索引,查询可以更快地执行。

WHERE (mile > @startMile OR mile = @startMile AND yard >= @startYard)
AND (mile < @endMile OR mile = @endMile AND yard <= @endYard)