表:
卡编号 剩余次数  时间
001   53    2000-1-1
001   52    2001-1-2
001     10    2002-1-1
002   80    2000-1-1
002   70    2001-1-1
要求显示:
001   10   2002-1-1
002   70   2001-1-1即每个卡号的最新的剩余次数
select *
from tb t
where not exists(select 1 from tb where 卡编号=t.卡编号 and 时间>t.时间)select 卡编号,min(剩余次数),max(时间) from 表
group by 卡编号 
order by 卡编号用上面两条sql语句,都不行,一个是超时,查不出来。另一个用MAX,和MIN,结果选出来的记录不对应,因为卡是循环使用的。用到0之后又要重复充值数值变大。

卡    次数      日期    时间
001  50    2010-1-4  16:00
001  49    2010-1-4   16:01
        。
001   0     2010-2-1    17:00
001   50    2010-2-2   1:00
002
003
004

解决方案 »

  1.   

    select *
    from tb t
    where not exists(select 1 from tb where 卡编号=t.卡编号 and 卡编号>t.卡编号)
      

  2.   

    select *
    from tb t
    where 时间=(select top 1 时间 from tb where 卡编号=t.卡编号 order by 时间 desc)
      

  3.   


    select *
    from tb t
    where 时间 = (select max(时间)from tb where 卡编号=t.卡编号 )用非关联的子句试试看
      

  4.   

    select t1.卡编号,t1.剩余次数,t1.时间 from tb t1
    inner join 
    (select 卡编号,max(时间) as 时间 from tb) t2 on a.卡编号=b.卡编号 and a.时间=b.时间
      

  5.   

    create table #test
    (编号 varchar(3),
    剩余次数 int,
    时间 datetime)insert #test
    select '001',53,'2000-1-1' union all
    select '001',52,'2000-1-2' union all
    select '001',10,'2002-1-1' union all
    select '002',80,'2000-1-1' union all
    select '002',70,'2001-1-1' 
    select 编号,剩余次数,时间 from (
    select 编号,剩余次数,时间,(select count(*) from #test  b
    where a.编号=b.编号 and a.时间<=b.时间) as rn
    from #test a) a
    where rn=1
      

  6.   


    --sql 2005
    select 卡编号,剩余次数,时间,row_number() over(partition by 卡编号 order by 时间 desc ) rn
    from table
    where rn=1
      

  7.   


    if object_id('[test]') is not null drop table [test]
    go
    create table test
    (
    ID varchar(3),
    Num int,
    CTime datetime
    )
    go
    insert test
    select '001',53,'2000-1-1' union all
    select '001',52,'2000-1-1' union all
    select '001',10,'2002-1-1' union all
    select '002',80,'2000-1-1' union all
    select '002',70,'2001-1-1' 
    go--查询---
    select a.ID,a.Num,a.CTime from test a
    inner join (
    select max(CTime) as CTime ,id from test group by id   
    ) b on a.id=b.id and a.CTime=b.CTime 
    order by a.ID--结果---
    ID Num CTime
    001 10 2002-01-01 00:00:00.000
    002 70 2001-01-01 00:00:00.000(2 行受影响)