日期:2014-05-18  浏览次数:20515 次

查询统计记录问题?


    地名         顺序
      A地             1
      B地             2
      C地             3
      D地             4
      E地             5
      F地             6
      G地             7
      H地             8

现要实现:我任意输入两个地点,要查找之间的所有地方。这个查询怎么实现。我用between   不起作用,   谢谢。

------解决方案--------------------
select * from 表
where 顺序 between (select 顺序 from 表 where 地名= 'B地 ')
and (select 顺序 from 表 where 地名= 'D地 ')
------解决方案--------------------
//借用一下楼上代码
应该是这样吧:
select * from 表
where (顺序 between (select 顺序 from 表 where 地名= 'B地 ')
and (select 顺序 from 表 where 地名= 'D地 '))
or
(顺序 between (select 顺序 from 表 where 地名=D地 ')
and (select 顺序 from 表 where 地名= 'B地 '))

------解决方案--------------------

select * from 表
where 顺序 between (select min(顺序) from 表 where 地名 in( 'B地 ', 'D地 '))
and (select max(顺序) from 表 where 地名 in( 'B地 ', 'D地 '))
------解决方案--------------------
if object_id( 'pubs..tb ') is not null
drop table tb
go

create table tb(地名 varchar(10),顺序 int)
insert into tb(地名,顺序) values( 'A地 ', 1)
insert into tb(地名,顺序) values( 'B地 ', 2)
insert into tb(地名,顺序) values( 'C地 ', 3)
insert into tb(地名,顺序) values( 'D地 ', 4)
insert into tb(地名,顺序) values( 'E地 ', 5)
insert into tb(地名,顺序) values( 'F地 ', 6)
insert into tb(地名,顺序) values( 'G地 ', 7)
insert into tb(地名,顺序) values( 'H地 ', 8)
go
declare @地名1 as varchar(10)
declare @地名2 as varchar(10)
set @地名1 = 'B地 '
set @地名2 = 'H地 '

select * from tb where 顺序 > = (select 顺序 from tb where 地名 = @地名1) and 顺序 <= (select 顺序 from tb where 地名 = @地名2)

drop table tb

/*
地名 顺序
---------- -----------
B地 2
C地 3
D地 4
E地 5
F地 6
G地 7
H地 8

(所影响的行数为 7 行)

*/
------解决方案--------------------
--结果如下:
/*
B地 2 2
C地 3 3
D地 4 4
E地 5 5
F地 6 6
C地 2 10
D地 3 11
E地 4 12
F地 5 13
*/
------解决方案--------------------
--try
if object_id( 'pubs..tb ') is not null
drop table tb
go

create table tb(id INT,地名 varchar(10),顺序 int,Aid int)
insert into tb(id,地名,顺序,Aid) values(1, 'A地 ', 1,1)
insert into tb(id,地名,顺序,Aid) values(1, 'B地 ', 2,2)
insert into tb(id,地名,顺序,Aid) values(1, 'C地 ', 3,3)
insert into tb(id,地名,顺序,Aid) values(1, 'D地 ', 4,4)
insert into tb(id,地名,顺序,Aid) values(1, 'E地 ', 5,5)
insert into tb(id,地名,顺序,Aid) values(1, 'F地 ', 6,6)
insert into tb(id,地名,顺序,Aid) values(1, 'G地 ', 7,7)