mysql取摸个字段值相同最多的记录_SQL语句--找出相同字段中的记录集中,另一字段为最大值的那条记录...

一个表tmp2

gh            bm            rq

1            3            2002-08-09  00:00:00.000

3            1            2002-09-01  00:00:00.000

4            4            2002-07-01  00:00:00.000

1            4            2002-07-05  00:00:00.000

3            2            2002-08-09  00:00:00.000

想要结果:

gh            bm            rq

4            4            2002-07-01  00:00:00.000

3            2            2002-08-09  00:00:00.000

1            3            2002-08-09  00:00:00.000

也就是说找出8月以前的rq最大的gh

我现在用的是:

select  a.*  from  tmp2  a  join  (select  gh,max(rq)  rq  from  tmp2  where  month(rq)<=8  group  by  gh)  b

on  a.gh=b.gh  and  a.rq=b.rq

还可不可以简化?

---------------------------------------------------------------

Select  Max(gh)  as  gh,  bm,  rq

From  tmp2

Where  Month(rq)<=8

Group  By  bm,  rq

试试看

---------------------------------------------------------------

month(rq)<=8的用法跨年度是不行的:

select  *  from  tmp2  a

where  rq

and  rq=(select  max(rq)  from  tmp2  where  gh=a.gh  and  rq

---------------------------------------------------------------

为什么不能找出所有小于8月的数据后,按日期反向排序,然后找到第一笔记录?

select  *  from  tmp2  a

where  rq

and  rownum  =  1

order  by  rq  desc

我没实验,如果ORACLE是先取结果集再排序这个想法就错了,但大家可以按照我这个思路想想,以前用SQL  SERVER的TOP  与  ORDER  BY  组合就能产生这样的效果

---------------------------------------------------------------

为什嬷不以gh分组,来查分组里最大的日期。

select  gh,max(rq)  rq  from  tmp2  where  rq

group  by  gh  order  by  gh  desc

---------------------------------------------------------------

上面的WHERE后RQ判断有问题

select  distinct  *  from  tmp2  a

where  rq

and  rq=(select  max(rq)  from  tmp2  where  gh=a.gh)

order  by  gh  desc

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值