查找相同ID最大时间的价格

hb1122 2010-07-23 01:43:06
表1:item_price
fields:
item_ID char(10);
price int;
utime datetime

内容如:
item_ID,price,utime
a125232541,12,2010-02-05 08:03:05
a125232541,18,2010-02-05 08:07:05
a125232541,9,2010-02-05 09:35:05
a125232542,128,2010-03-05 08:07:05
a125232542,19,2010-03-05 09:35:05
......

需求查询结果:
item_ID,price,utime
a125232541,9,2010-02-05 09:35:05
a125232542,19,2010-03-05 09:35:05
......

现在使用查询语句:
select item_ID, price, utime from item_price where item_ID + cast(utime as nvarchar) in (select item_ID + cast(max(utime) as nvarchar) from item_price group by item_ID)


由于批量运行,数据量大,感觉这语句运行起来速度慢慢的,求最有效率之查询方法。
不胜感激!
...全文
181 17 打赏 收藏 转发到动态 举报
写回复
用AI写文章
17 条回复
切换为时间正序
请发表友善的回复…
发表回复
cxmcxm 2010-07-23
  • 打赏
  • 举报
回复
--设表名为t
select a.* from t a,(select item_id,max(utime) utime from t group by item_id) b
where a.item_id=b.item_id and a.utime=b.utime
加油馒头 2010-07-23
  • 打赏
  • 举报
回复
select item_ID, price, utime from item_price where item_ID + cast(utime as nvarchar) in (select item_ID + cast(max(utime) as nvarchar) from item_price group by item_ID)


上面慢可能是 每个语句都要拼字符串吧
select item_ID, max(utime),max(price) from item_price group by item_ID,utime
hb1122 2010-07-23
  • 打赏
  • 举报
回复
[Quote=引用 14 楼 jaylongli 的回复:]
目前 只想到group by 方法
[/Quote]

我汗一个!
加油馒头 2010-07-23
  • 打赏
  • 举报
回复
目前 只想到group by 方法
hb1122 2010-07-23
  • 打赏
  • 举报
回复
[Quote=引用 12 楼 xiaoxiao8372 的回复:]
引用 1 楼 bancxc 的回复:

SQL code
select * from
tb t where not exists
(
select 1 from tb where t.item_ID=item_ID and t.utime<utime
)

这个快啊!!
[/Quote]

你试试偶的,就发现哪个快了!
xiaoxiao8372 2010-07-23
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 bancxc 的回复:]

SQL code
select * from
tb t where not exists
(
select 1 from tb where t.item_ID=item_ID and t.utime<utime
)
[/Quote]
这个快啊!!
hb1122 2010-07-23
  • 打赏
  • 举报
回复
[Quote=引用 10 楼 wxf163 的回复:]
SQL code
(.人.)
( 。人 。)
[/Quote]

熟人?貌似不认识!
王向飞 2010-07-23
  • 打赏
  • 举报
回复
(.人.)
( 。人 。)
hb1122 2010-07-23
  • 打赏
  • 举报
回复
[Quote=引用 5 楼 bancxc 的回复:]
试一下哪个快
[/Quote]

都还没我的快,汗!
CXZ84 2010-07-23
  • 打赏
  • 举报
回复
select item_ID,price,max(utime) from item_price
group by item_ID,price
然后再建立相应的索引加快查询的速度
aaron_gl 2010-07-23
  • 打赏
  • 举报
回复

仅供参考,
select item_ID, max(utime), max(price) from item_price group by item_ID,utime
百年树人 2010-07-23
  • 打赏
  • 举报
回复
在时间字段上建索引,查询的时候不要对时间字段使用函数
bancxc 2010-07-23
  • 打赏
  • 举报
回复
试一下哪个快
Mr_Nice 2010-07-23
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 bancxc 的回复:]

SQL code
select * from
tb t where not exists
(
select 1 from tb where t.item_ID=item_ID and t.utime<utime
)
[/Quote]

up
bancxc 2010-07-23
  • 打赏
  • 举报
回复
select * from 
tb t1 where utime in
(
select max(t2.utime) from tb t2 where t1.item_ID=t2.item_ID
)
  • 打赏
  • 举报
回复

呵呵……
bancxc 2010-07-23
  • 打赏
  • 举报
回复
select * from 
tb t where not exists
(
select 1 from tb where t.item_ID=item_ID and t.utime<utime
)

34,587

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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