复杂的sql语句求助,取最大及最小和取余的记录

conis 2010-01-28 08:55:21
现有数据如下:
Search_ID ts_Date ts_type ts_Counter
146 1/7/2010 0 0
151 1/8/2010 0 1
156 1/9/2010 0 2
161 1/10/2010 0 3
162 1/10/2010 0 4
167 1/11/2010 0 5
172 1/12/2010 0 6
177 1/13/2010 0 7
183 1/14/2010 0 8
189 1/15/2010 0 9
195 1/16/2010 0 10
201 1/17/2010 0 11
207 1/18/2010 0 12
213 1/19/2010 0 13
223 1/20/2010 0 14
235 1/21/2010 0 15
251 1/22/2010 0 16
258 1/23/2010 0 17
265 1/24/2010 0 18
272 1/25/2010 0 19
531 1/27/2010 0 20
401 1/7/2010 1 0
411 1/9/2010 1 1
416 1/10/2010 1 2
421 1/11/2010 1 3
426 1/12/2010 1 4
431 1/13/2010 1 5
437 1/14/2010 1 6
443 1/15/2010 1 7
449 1/16/2010 1 8
455 1/17/2010 1 9
461 1/18/2010 1 10
467 1/19/2010 1 11
477 1/20/2010 1 12
489 1/21/2010 1 13
505 1/22/2010 1 14
512 1/23/2010 1 15
519 1/24/2010 1 16
526 1/25/2010 1 17


要求根据条件取每个不同ts_type的记录,条件如下:
1.ts_Counter值最小的记录
2.ts_Counter值最大的记录
3.ts_Counter值整除5的记录

正确的结果如下:

Search_ID ts_Date ts_type ts_Counter
146 1/7/2010 0 0
167 1/11/2010 0 5
195 1/16/2010 0 10
235 1/21/2010 0 15
531 1/27/2010 0 20
401 1/7/2010 1 0
431 1/13/2010 1 5
461 1/18/2010 1 10
512 1/23/2010 1 15
526 1/25/2010 1 17


对SQL语句的要求:
1.尽可能的简单,性能尽可能地优化
2.尽量不采用临时表,游标,in之类的

当然,最终的目标是性能,并非一定不能使用in之类的
...全文
363 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
blue_java_ 2011-07-11
  • 打赏
  • 举报
回复
受教了,呵呵
purple3196 2010-01-28
  • 打赏
  • 举报
回复
select * from table a where ts_Counter%5=0
union all
select * from table a where ts_Counter = (select min(ts_Counter) from table)
union all
select * from table a where ts_Counter = (select max(ts_Counter) from table)
wwwwb 2010-01-28
  • 打赏
  • 举报
回复
select a.* from tt a inner join
(select ts_type,min(ts_Counter) as mi,max(ts_Counter) as ma from tt
group by ts_type) b
on a.ts_type=b.ts_type and ((a.ts_Counter=b.ma) or (a.ts_Counter=b.mi)
(or mod(a.ts_Counter,5)=0)
conis 2010-01-28
  • 打赏
  • 举报
回复
呵呵,别忘记了还有一个ts_type限制,而且这个ts_type可能很多个,也就是说,要取出每个不同ts_type的最大值和最小值
ACMAIN_CHM 2010-01-28
  • 打赏
  • 举报
回复
select *
from table1 a
where ts_Counter%5=0
or ts_Counter = (select min(ts_Counter) from table1)
or ts_Counter = (select max(ts_Counter) from table1)

56,677

社区成员

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

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