Microsoft SQL Server 2000数据库有一个名为XFJ的表,部分数据如下
卡号 终端号  消费金额 余额 消费时间                        消费类型
"12259 21 100 100 2009-11-28 11:14:51.000 消费"
"12259 21 -100 200 2009-11-28 11:14:56.000 充值"
"12259 22 100 100 2009-11-28 11:15:00.000 消费"
"12259 22 -100 200 2009-11-28 11:15:04.000 充值"
"12261 22 400 10 2009-11-28 21:17:57.000 消费"
"12222 22 400 0 2009-11-28 21:22:57.000 消费"因为卡号和消费记录数据较多,现在想查询每张卡的余额(也就是表记录中最后消费时间的余额数取出来),余额为0的不显示。以上数据应返回如下结果
"12259 22 -100 200 2009-11-28 11:15:04.000 充值"
"12261 22 400 10 2009-11-28 21:17:57.000 消费"我用以下的命令查询出来的结果有时候好像不能返回正确数据,明明那张卡余额已经为0了,但用下面的语法会出来余额230的记录,有时候又是正常的,不知道是什么原因
use xfj
select *, 余额 AS Expr1, 卡号 AS Expr2 from xfj where 消费时间 IN(SELECT max(消费时间) FROM xfj GROUP BY 卡号)
ORDER BY 余额 DESC, 卡号
麻烦高手帮忙写一个查询语句,谢谢!!
 

解决方案 »

  1.   


    --> 测试数据:[TB]
    if object_id('[TB]') is not null drop table [TB]
    create table [TB]([卡号] int,[终端号] int,[消费金额] int,[余额] int,[消费时间] datetime,[消费类型] varchar(4))
    insert [TB]
    select 12259,21,100,100,'2009-11-28 11:14:51.000','消费' union all
    select 12259,21,-100,200,'2009-11-28 11:14:56.000','充值' union all
    select 12259,22,100,100,'2009-11-28 11:15:00.000','消费' union all
    select 12259,22,-100,200,'2009-11-28 11:15:04.000','充值' union all
    select 12261,22,400,10,'2009-11-28 21:17:57.000','消费' union all
    select 12222,22,400,0,'2009-11-28 21:22:57.000','消费'select * from [TB] t where not exists(select 1 from TB where [卡号]=t.[卡号] and [消费时间]>t.[消费时间])
    /*
    卡号          终端号         消费金额        余额          消费时间                    消费类型
    ----------- ----------- ----------- ----------- ----------------------- ----
    12259       22          -100        200         2009-11-28 11:15:04.000 充值
    12261       22          400         10          2009-11-28 21:17:57.000 消费
    12222       22          400         0           2009-11-28 21:22:57.000 消费(3 行受影响)*/
    drop table TB
      

  2.   

    select
     * 
    from
     [TB] t 
    where
     消费时间=(select max(消费时间) from TB where [卡号]=t.[卡号])
      

  3.   

    select * from tb t
    where yue!=0 and not exits
    (select 1 from tb where yue!=0 and t.card=card and t.time<time)
      

  4.   

    --加个 余额 <> 过滤select * from [TB] t where 余额 <> 0 AND not exists(select 1 from TB where [卡号]=t.[卡号] and [消费时间]>t.[消费时间])
      

  5.   


    select *, 余额 AS Expr1, 卡号 AS Expr2 from xfj a where 消费时间 IN(SELECT max(消费时间) FROM xfj where 卡号 = a.卡号)
    where 余额 <> 0
    ORDER BY 余额 DESC, 卡号