MySQL计算行之间的差异并将结果写入列?

时间:2015-04-13 14:04:10

标签: mysql

我有一个我无法解决的问题,真的需要你的帮助!

我必须遵循表格;

mysql> describe inactivitytmp;
+----------+------------------+------+-----+---------+-------+ 
| Field    | Type             | Null | Key | Default | Extra | 
+----------+------------------+------+-----+---------+-------+ 
| user_id  | int(10) unsigned | NO   |     | NULL    |       | 
| start_ts | int(10) unsigned | NO   |     | NULL    |       | 
| end_ts   | int(10) unsigned | NO   |     | 0       |       | 
+----------+------------------+------+-----+---------+-------+ 
3 rows in set (0.01 sec)

表包含:用户数字,开始/结束unix时间戳。以下数据只是为了向您展示它的样子:

user_id;  start_ts;   end_ts;
1            150000    150010
1            160011    160050
1            160100    160200
2            150011    150023
2            155001    155055
2            160001    160500
3            159001    159550

我想计算一个名为diff的新列,它是start(row x + 1) - stop(row x)之间的差异。如果第x + 1行是与行x不同的用户,则diff = 0

所以我要找的结果是:

user start   stop  diff
1   150000 150010  160011-150010=10001
1   160011 160050  160100-160050
1   160100 160200  0 (new user on next row)
2   150011 150023  155001-150023
2   155001 155055  160001-155055
2   160001 160500  0 (new user on next row)
3   159001 159550  and so on..

在Stackowerflow上的上一个问题以及@fancyPants的大量帮助之后,我使用以下代码添加列,并将计算结果写入新列;

ALTER TABLE inactivitytmp add column diff int;

UPDATE inactivitytmp
JOIN (
SELECT inactivitytmp.*
 , if(@prev_user_id = `user_id`, (`end_ts` - @prev) * -1, 0) as diff2
 , @prev := `start_ts`
 , @prev_user_id := `user_id`
FROM inactivitytmp
 , (
SELECT @prev := null, @prev_user_id := null) var_int
ORDER BY `user_id`, `start_ts` DESC ) query_alias
ON inactivitytmp.user_id=query_alias.user_id AND inactivitytmp.start_ts=query_alias.start_ts AND inactivitytmp.end_ts=query_alias.end_ts
SET inactivitytmp.diff=query_alias.diff2;

问题是我无法理解的错误消息:

ERROR 1690 (22003): BIGINT UNSIGNED value is out of range in '(`database`.`inactivitytmp`.`end_ts` - (@`prev`))'

任何帮助都会得到满足!

AKE

0 个答案:

没有答案