在手机系统方案中,我有2张桌子。
customer_id
,call_duration
,calldate
,skip_billing
。customer_id
,bonus_seconds
。table1存储所有客户的所有呼叫,table2存储bonus_seconds,表示定义客户允许的免费通话时间(即:对于客户1,FIRST 40累积秒数是免费的)。
我必须根据下面解释的条件编写一个更新table1的查询: 在table2中免费定义的调用中设置skip_billing。
所以我首先需要按customer_id进行分组,然后迭代调用,在call_duration上递增累积变量(cumsec)并相应地设置skip_billing。
table1的例子是:
|sqlid |customer_id |billsec | skipbill|
|0 |1 |12 | 1 |<--need to set 1 due to cume=12 for customer_id=1
|1 |1 |10 | 1 |<--need to set 1 due to cume=22 for customer_id=1
|2 |1 |15 | 1 |<--need to set 1 due to cume=37 for customer_id=1
|3 |1 |8 | 0 |<--nop(no operation) due to cume=45
|4 |2 |12 | 1 |<--need to set 1 due to cume=12 for customer_id=2
|5 |3 |12 | 1 |<--need to set 1 due to cume=12 for customer_id=3
|6 |2 |12 | 0 |<--nop due to cume=24 for customer_id=2
|7 |1 |12 | 0 |<--nop due to cume=49 for customer_id=1
|8 |3 |15 | 0 |<--nop due to cumsec=27 for customer_id=3
|customer_id |bonus_seconds|
|1 |40 |
|2 |20 |
|3 |15 |
我尝试了这样的查询(感谢Gordon Linoff),它返回了正确的行集:
SELECT t.cume, t.calldate, t.customer_id FROM (SELECT t.*, (@cume := @cume + billsec) AS cume FROM table1 t CROSS JOIN (SELECT @cume := 0) vars ORDER BY calldate) t, table2 sct WHERE t.cume <= sct.bonus_seconds AND t.customer_id=sct.customer_id ;
但是,当我尝试使用UPDATE时,如下面的命令,它不起作用,因为不匹配任何东西。
UPDATE table1 SET skipbill=1 WHERE sqlid=(SELECT t.sqlid FROM (SELECT t.*, (@cume := @cume + billsec) AS cume FROM table1 t CROSS JOIN (SELECT @cume := 0) vars ORDER BY calldate) t, table2 sct WHERE t.cume <= sct.bonus_seconds AND t.customer_id=sct.customer_id ) ;
如何使用该查询或其他更好的方式编写更新任务?
提前谢谢
答案 0 :(得分:1)
在我看来,你要为客户1(例如)收费3秒,这应该是他们奖金的一部分,但无论如何......
SELECT x.*
, SUM(y.billsec) cumu
, IF(SUM(y.billsec)<=z.bonus_seconds,1,0) n
FROM my_table x
JOIN my_table y
ON y.customer_id = x.customer_id
AND y.sqlid <= x.sqlid
LEFT
JOIN bonus z
ON z.customer_id = x.customer_id
GROUP
BY x.customer_id
, x.sqlid
ORDER
BY sqlid;
答案 1 :(得分:1)
UPDATE table1
SET skipbill = 1
WHERE sqlid IN (
SELECT DISTINCT t.sqlid
FROM (
SELECT t.*, (@cume := @cume + billsec) AS cume
FROM table1 t
CROSS JOIN (SELECT @cume := 0) vars
ORDER BY calldate
) t, table2 sct
WHERE t.cume <= sct.bonus_seconds
AND t.customer_id = sct.customer_id
);