不同条件的分组查询sql

xuanjie25 2013-09-01 02:47:40
例如我有一张表table,表的数据如下:
code lastupdatetime
006939828 2013-08-29
006939828 2013-08-27
006939828 2013-08-26
006939828 2013-08-26
006940116 2013-08-27
006940116 2013-08-27
006940116 2013-08-29
696453330 2013-08-28
696453330 2013-08-27
696453330 2013-08-29


我想查询表中不同code的数量,我用下面的语句来查:
select count(*) as num, tb.code as code from table tb
where tb.code in('006939828','006940116','696453330')
group by tb.code;
结果是:
num code
4 006939828
3 006940116
3 696453330

其中in里面的code字段是通过其他表查出来的,现在我想增加一个时间限制,即查询某个时间之前的不同code的数量,时间不止一个,而是每个code都有一个时间,例如查006939828是在2013-08-27之前的,而006940116是在2013-08-28之前的,请问应该怎么实现?谢谢各位!
...全文
314 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复
如果你的code能跟你的时间段通过某个字段对应上,那么你可以在查询code的时候进行过滤
xuanjie25 2013-09-01
  • 打赏
  • 举报
回复
引用 3 楼 zhuhl2011 的回复:
你那个需要查询的时间可以固定下来的吗? 如果可以的话 在你那个查询code的表里面 增加一个字段 是查询时间的字段就可以实现了

select count(*) as num, tb.code as code from table tb 
 where 
exists (select 1 from tableA taa
   where taa.code = tb.code
     and tb.lastupdatetime < taa.lastupdatetime)
 group by tb.code;
这样就可以实现你的要求
谢谢回复,不可以
xuanjie25 2013-09-01
  • 打赏
  • 举报
回复
引用 4 楼 ssqtjffcu1 的回复:
各个code的时间是固定的么,或者可以通过在数据库里存储各个code的时间,然后用表关联。楼主最好先把各个code的时间是怎么产生的说清楚,好解决问题。
谢谢回复 code lastupdatetime 006939828 2013-08-29 006939828 2013-08-27 表里面的时间是最后更新时间,但需要比较的那个时间,是我从另一张表取得的,表中的数据如下: lastupdatetime code depcode 2013-08-30 006939828 ex_gdbs_sl 2013-08-31 006939828 ex_gdbs_sl 2013-07-23 006940116 ex_gdbs_sl 时间是取相同code,相同depcode的最大时间,例如上面的数据,code为006939828的时间是2013-08-31,code为006940116的时间是2013-07-23 那么我要查的是code为006939828,时间小于2013-08-31的数据量,不知道这样说是不是清楚
ssqtjffcu 2013-09-01
  • 打赏
  • 举报
回复
各个code的时间是固定的么,或者可以通过在数据库里存储各个code的时间,然后用表关联。楼主最好先把各个code的时间是怎么产生的说清楚,好解决问题。
zhuhl2011 2013-09-01
  • 打赏
  • 举报
回复
你那个需要查询的时间可以固定下来的吗? 如果可以的话 在你那个查询code的表里面 增加一个字段 是查询时间的字段就可以实现了

select count(*) as num, tb.code as code from table tb 
 where 
exists (select 1 from tableA taa
   where taa.code = tb.code
     and tb.lastupdatetime < taa.lastupdatetime)
 group by tb.code;
这样就可以实现你的要求
xuanjie25 2013-09-01
  • 打赏
  • 举报
回复
引用 1 楼 youqi1984 的回复:
把你count(*) 换成 count( case when code='006939828' and date<'2013-08-27' then 1 case when code='006940116' and date<'2013-08-28' then 1 else 0 )
谢谢回复,这种方式有想过,但是code有好多个,这样就需要拼接sql了,不知道有没有其他好点的方式?
youqi1984 2013-09-01
  • 打赏
  • 举报
回复
把你count(*) 换成 count( case when code='006939828' and date<'2013-08-27' then 1 case when code='006940116' and date<'2013-08-28' then 1 else 0 )

17,377

社区成员

发帖
与我相关
我的任务
社区描述
Oracle 基础和管理
社区管理员
  • 基础和管理社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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