高手看过来,不是难题不求人!!!高分求查询语句!!!!! 分不够可再加!!!

chx007 2002-08-23 04:18:14
设表tab1结构如下:
字段 类型 主键
id char(7) Y
name char(10) N

设表tab2结构如下:
字段 类型 主键 外键
id char(7) Y Y
time datetime Y N
value numeric(8,3)N N

现在要查询出每个id点,在所给定的起始时间到终止时间的区间中,

最大时间(<=终止时间)所在的value减去最小时间(>=起始时间)所在的value后的差值,

如果最大时间所在的value与最小时间所在的value有一个以上未找到,则该差值为0,

如起始时间为'2002-8-1',终止时间'2002-8-23' 要求的返回结果集如下:

tab1.name 差值

'a' 10
'b' 20
: :
: :
: :

注意:tab2表的数据量效大,差不多在一百万条左右,所以,不得不考虑查询效率的问题!
...全文
24 14 打赏 收藏 转发到动态 举报
写回复
用AI写文章
14 条回复
切换为时间正序
请发表友善的回复…
发表回复
demiurge 2002-08-26
  • 打赏
  • 举报
回复
select id, isnull(select value from tab2 b where id = a.id and time = :stime), 0) -
isnull(select value from tab2 b where id = a.id and time = :etime), 0)
from tab1 a
demiurge 2002-08-26
  • 打赏
  • 举报
回复
select id, isnull(select value from tab2 b where id = a.id and time = (select max(time) from tab2 c where c. id = a.id), 0) -
isnull(select value from tab2 b where id = a.id and time = (select min(time) from tab2 c where c. id = a.id), 0)
from tab1 a
bobfang 2002-08-24
  • 打赏
  • 举报
回复
select id,max(time) max_time,min(time) min_time
into #temp
from tab2
where time between '2002-8-1' and '2002-8-24'
group by id

select tab1.name,isnull(b.value-c.value,0)
from tab1 ,#temp a,tab2 b,tab2 c
where tab1.id = a.id
and a.id = b.id and a.max_time = b.time
and a.id = c.id and a.min_time = c.time
union
select tab1.name,0
from tab1
where not exists(select 1 from #temp where tab1.id=#temp.id)
studyfor 2002-08-23
  • 打赏
  • 举报
回复
rich_li(rick) 的这个方案可以,但是你要测一下这个语句的效率:
select id,max(time) max_time,min(time) min_time
into #temp
from tab1.name
group by id 另外你也可以将这句话建成view,这样只要下面这个语句就行了,不用存储过程了。


下面这条语句执行效率应该很快,如你所说#temp表中不会大于70×2=140条记录,效率应该不错。
select a.id,isnull(b.value-c.value,0)
from #temp a,tab1.name b,tab1.name c
where a.id = b.id and a.max_time = b.time
and a.id = c.id and a.min_time = c.time

brook_huang 2002-08-23
  • 打赏
  • 举报
回复
自己写SP呀,需要用到游标,可能会比较烦的
chx007 2002-08-23
  • 打赏
  • 举报
回复
tab1大概有60多条!
rich_li 2002-08-23
  • 打赏
  • 举报
回复
select id,max(time) max_time,min(time) min_time
into #temp
from tab1.name
group by id

select a.id,isnull(b.value-c.value,0)
from #temp a,tab1.name b,tab1.name c
where a.id = b.id and a.max_time = b.time
and a.id = c.id and a.min_time = c.time
zhangxhsj 2002-08-23
  • 打赏
  • 举报
回复
别着急,晚上我给出答案。
zcflion 2002-08-23
  • 打赏
  • 举报
回复
版主快出来看一下,怎么能躲起来呢!!??负责任点嘛!
studyfor 2002-08-23
  • 打赏
  • 举报
回复
SQL SERVER???
发错地方了吧???

tab1 大概有多少条记录?
chx007 2002-08-23
  • 打赏
  • 举报
回复
忘了说了,我用的是MS SQL SERVER 平台

并不一定非得是单纯SQL语句,也可以是存储过程等其他方式,只要速度快,甚至你要是认为表结构不合理,也可以提出修改建议!
zcflion 2002-08-23
  • 打赏
  • 举报
回复
关注得流鼻血了!
呵呵
chx007 2002-08-23
  • 打赏
  • 举报
回复
当然可以啊,只速度快就行!!我现在是可以实现但是速度大慢了,很不理想!!
studyfor 2002-08-23
  • 打赏
  • 举报
回复
必须用sql语句吗?

procedure 行不?要是用sql语句效率很难保证啊。因为你在tab2上毕竟要做一个table scan

2,596

社区成员

发帖
与我相关
我的任务
社区描述
Sybase相关技术讨论区
社区管理员
  • Sybase社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧