日期:2014-05-18 浏览次数:20479 次
select CONVERT(nvarchar(10), Time1, 20) as Time2,usercode,(0-sum(money)) from [table] group by usercode,CONVERT(nvarchar(10), time1, 20) order by time2
select CONVERT(nvarchar(10), Time1, 20) as Time2,usercode,(0-sum(money)),max(id) as lastid from [table] group by usercode,CONVERT(nvarchar(10), time1, 20) order by time2
select CONVERT(nvarchar(10), Time1, 20) as Time2, usercode,(0-sum(money)), lastbalance=(select top 1 balance from [table] where usercode=t.usercode and CONVERT(nvarchar(10),time1,20)=CONVERT(nvarchar(10),time1,20) order by id desc) from [table] t group by usercode,CONVERT(nvarchar(10), time1, 20) order by time2
------解决方案--------------------
只需要找出time1最大的那条记录,然后把会员名相同的“消费金额”sum起来就可以了,但是前提是你的time1要保证没有一模一样的。
select sum(balance)*(-1)
from 表 as a
where time1 In (select max (time1) from 表) and balance<0
group by 会员名
解释:select中乘以-1是为了在显示时能显示出金额,而不是负数。不直观。如果你的业务需要显示负数,可以取消乘以-1。
where time1 In (select max (time1) from 表)是为了找出最后一笔记录所对应的会员名,balance<0就是为了只找出消费金额。
如有漏洞。请指出。谢谢。
对于select top 1 *测试了一下,时间的确快一点。不过从关系数据库理论来说,top 还包含了排序与distinct,所以如果时间差不多,不写也行。