单表group的统计问题。。。如何取一天的最后条记录?
表结构如下:
id time1【时间】 usercode【会员名】 money【金额】 balance【余额】
如此,要统计查询时间内,单天的会员的消费金额,及【当天的最后余额】情况。
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,所以如果时间差不多,不写也行。