我有一个以EID作为主键的表(它是一个varchar并包含一些细节)和uploadtime作为日期时间列。我希望这张表的结果为:
substr(eid,5,5) as machine | count(eid) in group(grouped by machine) as packets | AvgDelay (as shown in SQL code) | packets * AvgDelay as Penalty
但是最后一列始终为null。我使用的SQL是:
SELECT substr(eid, 5, 5) AS machine,
@packetcount: = count(*) AS packets,
@avg_delay: = round(avg(DATEDIFF(IF (STR_TO_DATE(uploadtime, '%Y-%m-%d') IS NULL, CURDATE(), STR_TO_DATE(uploadtime, '%Y-%m-%d')), STR_TO_DATE(SUBSTR(eid, 15, 8), '%Y%m%d') ) ) ) AS AvgDelay,
@packetcount * @avg_delay AS Penalty
FROM eidreport
WHERE uploadtime IS NOT NULL
OR DATEDIFF(IF (STR_TO_DATE(uploadtime, '%Y-%m-%d') IS NULL, CURDATE(), STR_TO_DATE(uploadtime, '%Y-%m-%d')), STR_TO_DATE(SUBSTR(eid, 15, 8), '%Y%m%d') ) >= 100
GROUP BY machine
Here is the link for SQL Fiddle
我哪里错了?请帮忙。提前谢谢。
答案 0 :(得分:0)
我认为这里的问题在GROUP BY
声明中。我认为@packetcount: = count(*)
在分组之后计算但@packetcount * @avg_delay
之前计算,所以在这一刻它们是未定义的。
尝试使用这样的子查询:
SELECT *,
packets * AvgDelay AS Penalty
FROM
(
select substr(eid,5,5) as machine,count(*) as packets,
round(avg(DATEDIFF(IF(STR_TO_DATE(uploadtime, '%Y-%m-%d') IS NULL, CURDATE(), STR_TO_DATE(uploadtime, '%Y-%m-%d')),
STR_TO_DATE(SUBSTR(eid, 15, 8),'%Y%m%d')))) AS AvgDelay
from eidreport
where uploadtime is not null or
DATEDIFF(
IF(STR_TO_DATE(uploadtime, '%Y-%m-%d') IS NULL, CURDATE(), STR_TO_DATE(uploadtime, '%Y-%m-%d')),
STR_TO_DATE(SUBSTR(eid, 15, 8),'%Y%m%d')) >= 100
group by machine
) as T
答案 1 :(得分:0)
为什么在不需要时使用子查询:
SELECT
SUBSTR(eid,5,5) machine,
COUNT(1) packets,
ROUND(AVG(DATEDIFF(IF (STR_TO_DATE(uploadtime, '%Y-%m-%d') IS NULL,
CURDATE(), STR_TO_DATE(uploadtime, '%Y-%m-%d')),
STR_TO_DATE(SUBSTR(eid, 15, 8), '%Y%m%d') ) ) ) AvgDelay,
COUNT(1) * ROUND(AVG(DATEDIFF(IF (STR_TO_DATE(uploadtime, '%Y-%m-%d') IS NULL,
CURDATE(), STR_TO_DATE(uploadtime, '%Y-%m-%d')),
STR_TO_DATE(SUBSTR(eid, 15, 8), '%Y%m%d') ) ) ) Penalty
FROM
eidreport
WHERE uploadtime IS NOT NULL
OR DATEDIFF(IF (STR_TO_DATE(uploadtime, '%Y-%m-%d') IS NULL, CURDATE(),
STR_TO_DATE(uploadtime, '%Y-%m-%d')),
STR_TO_DATE(SUBSTR(eid, 15, 8), '%Y%m%d') ) >= 100
GROUP BY machine
optimers仅评估相同的表达式