我有以下表格,我正在努力获得正确的查询:
活动表:
ID USER_ID CARD_ID CLOCK
1 123 04675545 4/3/2013 1:07:06 PM
2 123 04675545 4/3/2013 2:08:06 PM
3 124 04675550 4/3/2013 2:07:06 PM
4 124 04675550 4/3/2013 4:07:06 PM
** 价格表:
ID FROMTIME TOTIME PRICEPERHOUR
1 08:00:00 19:59:59 50.00
2 20:00:00 07:59:59 75.00
我正在尝试创建一个程序,告诉我每个用户每天花费的金额基于每小时的费用和每天的总活动。一旦我有了正确的查询,我就会将其插入到事务表中。
关于什么是最佳做法的任何想法?非常感谢能得到帮助的人。
答案 0 :(得分:3)
尝试此查询
如果要创建存储过程,可以从给定查询创建...
select a.user_id, date(a.clock), ABS(TIME_TO_SEC(TIMEDIFF(a.clock, b.clock))/3600)*c.PRICEPERHOUR as total from
(Select if((@rn:=@rn+1)%2=0,@rn,@rn-1) As rId, act.* from act
join
(select @rn:=-1)a
order by user_Id, clock) a
inner join
(Select if((@rn1:=@rn1+1)%2=0,@rn1,@rn1-1) As rId, act.* from act
join
(select @rn1:=-1)b
order by user_Id, clock) b
ON a.rid=b.rid AND a.id <> b.id
inner join
price c
on
TIME_TO_SEC(a.clock) between TIME_TO_SEC(c.FROMTIME)
AND
TIME_TO_SEC(c.TOTIME)
group by a.user_id, date(a.clock)
<强>结果:
| USER_ID | DATE(A.CLOCK) | TOTAL |
----------------------------------------------------
| 123 | April, 03 2013 00:00:00+0000 | 50.8333 |
| 124 | April, 03 2013 00:00:00+0000 | 100 |