日期:2014-05-17  浏览次数:20699 次

不同条件的分组查询sql
例如我有一张表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之前的,请问应该怎么实现?谢谢各位!

------解决方案--------------------
把你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的表里面 增加一个字段  是查询时间的字段就可以实现了

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;

这样就可以实现你的要求
------解决方案--------------------
各个code的时间是固定的么,或者可以通过在数据库里存储各个code的时间,然后用表关联。楼主最好先把各个code的时间是怎么产生的说清楚,好解决问题。
------解决方案--------------------