SQL查询有多张银行卡,每张卡每天都收入支出了很多次,查询每张卡当天的最终余额(当天最后一次操作后的余额

有多张银行卡,每张卡每天都收入支出了很多次,查询每张卡当天的最终余额(当天最后一次操作后的余额,注意是每张卡,不是一张卡),在mybits怎么写SQL语句? 字段有:bankCardNum(卡号),operTime(操作时间),operMoney(操作金额),type(操作类型)(1为收入2为支出),balance(余额)

收入次数 (时间 '2013-04-19',的次数)
select count(*) from 卡表名 where type = 1 and operTime > '2013-04-19' and operTime< '2013-04-20'
支出次数 (时间 '2013-04-19',的次数)
select count(*) from 卡表名 where type = 2 and operTime > '2013-04-19' and operTime< '2013-04-20'
余额 (时间 '2013-04-19',的余额)
select balance from 卡表名 where operTime > '2013-04-19' and operTime< '2013-04-20' order by id desc追问

你这个是把全部的余额都差出来了,我要的是当天最后一次操作后的余额,而且是所有卡的最后一次操作时间后的余额

追答

select top 1 balance from 卡表名 where operTime > '2013-04-19' and operTime< '2013-04-20' order by id desc

温馨提示:答案为网友推荐,仅供参考
第1个回答  2013-04-19
如果你的operTime是时间型:
select distinct bankCardNum, balance,max(operTime) from 卡表名 where operTime=(select max(operTime) from 卡表名 group by bankCardNum) group by bankCardNum
第2个回答  2013-04-19
select bankCardNum,operTime,operMoney,type,balance ,max(operTime )from tb group by bankCardNum,operTime,operMoney,type,balance
第3个回答  2013-04-19
-- 所有卡的最后一次操作时间后的余额
select bankCardNum , balance

from card a

where not exists (
select 1 from card b
where b.bankCardNum = a.bankCardNum
and b.operTime > a.operTime)追问

 

时间还是不对呀,应该只显示当天的,这把全部的都给查出来了。

追答

-- 所有卡的最后一次操作时间后的余额
select bankCardNum , balance
from card a
where 1=1
and not exists (
select 1 from card b
where b.bankCardNum = a.bankCardNum
and b.operTime > a.operTime)
and operTime >= '2013-04-19'-- 如果是M$SQL, 可用 dateadd(day, datediff(day, 0, getdate()), 0) 替代 '2013-04-19'
-- 如果是SQLite, date('now') 表示“今天”, 若要考虑+8时区, date('now', '+8 hour')