我正在使用以下SQL。 column1,column2给出输出,如122.5014和4.2857;但最后一栏给出输出 NULL ,虽然我期待 48.9266 。
SQL INPUT:
SELECT (
SELECT @h := ( SUM( (
TIME_TO_SEC( TIMEDIFF( `stop` , `start` ) ) /3600 ) )
)
) AS `HoursWorked` , (
SELECT @w := ( TIMESTAMPDIFF(
DAY , MIN( `start` ) , MAX( `stop` ) ) /7 )
) AS `InWeeks` , (
SELECT (
((@w *40) - ( @h ))
)
) AS `DutyDistance`
FROM `work_table`
输出:
HoursWorked | InWeeks | DutyDistance
------------------------------------
122.5014 | 4.2857 | NULL
答案 0 :(得分:0)
使用聚合函数计算用户变量的输出是不可预测的,然后在表达式中使用。因此,您的查询无效。
示例:
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)
因此,您必须首先更改查询以在内部查询中计算HoursWorked
和InWeeks
,然后在外部查询中计算DutyDistance
。不需要用户变量。
示例:
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