带有WHERE CLAUSE的TIMESTAMPDIFF函数的MySQL AVG

时间:2014-07-07 15:24:42

标签: mysql sql timestamp average

我有一张表,我试图获得平均持续时间。我使用以下代码

/*TIME DURATION*/
SELECT DATE(createDate),
AVG(TIMESTAMPDIFF(SECOND, min(createDate), max(createDate))) AS Duration
FROM Impressions
WHERE session_id IN (
    SELECT session_id
    FROM carts
    WHERE createDate >= '2014-06-30'AND createDate < '2014-07-07'
        AND HOUR(createDate) >= 10
        AND HOUR(createDate) < 21
    )

AND session_Id <> ''
GROUP BY DATE(createDate);

但是,我收到以下错误,无法理解原因。任何帮助将不胜感激。

  
    

ErrorCode:-2147467259,Number:1111     ErrorMessage:无效使用组功能

  

1 个答案:

答案 0 :(得分:1)

我建议你使用这样的查询:

SELECT DATE(tbl.createDate),
       AVG(TIMESTAMPDIFF(SECOND, tbl.minDt, tbl.maxDt)) AS Duration  
  FROM (SELECT DATE(i.createDate) as createDate,
               min(i.createDate) minDt,
               max(i.createDate) maxDt
          FROM Impressions i INNER JOIN
               carts c ON (i.session_id = c.session_id)
         WHERE c.createDate >= '2014-06-30' 
           AND c.createDate < '2014-07-07'
           AND HOUR(c.createDate) >= 10
           AND HOUR(c.createDate) < 21
           AND i.session_Id <> ''
         GROUP BY DATE(i.createDate) ) as tbl
 GROUP BY DATE(tbl.createDate);