Output of user variables is not predictable when calculated with aggregate functions and then used in an expression. And hence, your query did not work.
Example:
mysql> create table tbl_so_q23870035( i int );
Query OK, 0 rows affected (0.48 sec)
mysql> insert into tbl_so_q23870035 values( 2 ), ( 4 ), ( 9 ), ( 6 ), ( 15 );
Query OK, 5 rows affected (0.13 sec)
Records: 5 Duplicates: 0 Warnings: 0
mysql> select @s:=sum(i) as s, @s*2 as s2 from tbl_so_q23870035;
+------+------+
| s | s2 |
+------+------+
| 36 | NULL |
+------+------+
1 row in set (0.00 sec)
mysql> select s, s*2 as s2
-> from (
-> select sum(i) as s from tbl_so_q23870035
-> ) aggregated_data;
+------+------+
| s | s2 |
+------+------+
| 36 | 72 |
+------+------+
1 row in set (0.00 sec)
Hence, you have to change your query first to calculate HoursWorked
, and InWeeks
in inner query and then secondly calculate DutyDistance
in outer query. No user variable is required.
Example:
select `HoursWorked`, `InWeeks`, ( `InWeeks` * 40 - `HoursWorked` ) AS `DutyDistance`
from (
select SUM( TIME_TO_SEC( TIMEDIFF( `stop`, `start` ) ) / 3600 ) AS `HoursWorked`
, TIMESTAMPDIFF( DAY , MIN( `start` ), MAX( `stop` ) ) / 7 AS `InWeeks`
FROM `work_table`
) aggregated_data