以前有人提过的问题,小第不是很明白,请大家来帮忙

老宛 2003-09-04 10:21:42
表有三列:AA(主健),BB(NVARCHAR),CC(DATETIME)
要求查询出的结果按BB值相同的放在一起(ORDER BY),同时按CC从大到小取前五行
如:BB字段有6个值是“TEST”那么只按CC取前5行


回复人: CrazyFor(太阳下山明朝依旧爬上来) ( ) 信誉:262 2003-08-22 10:58:00 得分:0


select * from 表 a where (select count(*) from 表 b where a.bb=b.bb and b.cc<=a.cc)<=5
这个语句我试了,但只能按cc从小到大来取前五行,谁能告诉我上面这个句子的执行过程,谢谢了!




...全文
32 11 打赏 收藏 转发到动态 举报
写回复
用AI写文章
11 条回复
切换为时间正序
请发表友善的回复…
发表回复
zarge 2003-09-04
  • 打赏
  • 举报
回复
select * from 表 a
where (select count(*) from 表 where bb=a.bb and cc>=a.cc) <= 5
order by bb, cc desc
chao778899 2003-09-04
  • 打赏
  • 举报
回复
select top 5 a.* from table9 a join
(select top 5 cc from table9 order by cc desc) b on a.cc=b.cc
order by bb [desc]
最后的DESC就看BB 和 CC的关系了,是同方向增长还是反方向
chao778899 2003-09-04
  • 打赏
  • 举报
回复
select top 5 * from table a where cc in(select top 5 cc from (select * from table order by bb) order by cc desc)
txlicenhe 2003-09-04
  • 打赏
  • 举报
回复
select * from table a where cc in
(select top 5 cc from table where aa=a.aa order by cc desc)
order by BB
老宛 2003-09-04
  • 打赏
  • 举报
回复
受pengdali(大力 V2.0)兄启发,小弟写了下面这句,请各位提出意见
select * from wys a
where aa in (select top 5 aa from wys where bb=a.bb order by cc desc)
order by bb,cc desc
chao778899 2003-09-04
  • 打赏
  • 举报
回复
select * from table a where cc in(select top 5 cc from (select * from table order by bb) order by cc desc)
愉快的登山者 2003-09-04
  • 打赏
  • 举报
回复
select * from 表 a
where (select count(*) from 表 where bb=a.bb and cc>=a.cc) <= 5
order by bb

取bb相同的,cc最大的前五个。
或:
select distinct * from 表 a
where cast(cc as char)+cast(aa as char) in (select top 5 cast(cc as char)+cast(aa as char) from 表 where bb=a.bb order by cc desc)
order by bb

老宛 2003-09-04
  • 打赏
  • 举报
回复
to:zgh2003(世纪飞扬)
你的这条语句和我上面写的基本上是一样的,只是我忘了排序了,这个还没有符合我的要求,这个语句不能把cc按从最大到最小取前五来排列,而是按从最小到最大取倒数五个来排列,谢谢你的支持,请继续支持

to:pengdali(大力 V2.0)
你的句子我也试了,没有完全符合要求,因为cc可能有很多是相同的,所以有时超过了5个,不过小弟非常感谢你,你写的很有创意,佩服佩服!再接再励!
happydreamer 2003-09-04
  • 打赏
  • 举报
回复
select * from table as A
where CC in ( select top 5 CC from table where AA=A.AA)

zgh2003 2003-09-04
  • 打赏
  • 举报
回复
select * from 表 a where (select count(*) from 表 b where a.bb=b.bb and b.cc<=a.cc)<=5 order by cc desc
pengdali 2003-09-04
  • 打赏
  • 举报
回复
select * from 表 a where cc in (select top 5 cc from 表 where bb=a.bb order cc desc)

34,576

社区成员

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

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