简体   繁体   中英

MySQL AVG of TIMESTAMPDIFF function with WHERE CLAUSE

I have a table from which I am trying to get the average duration. I am using the following code

/*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);

However, I am getting the following error and cannot understand why. Any help will be appreciated.

ErrorCode: -2147467259, Number: 1111 ErrorMessage: Invalid use of group function

I would recommend you to use the query like this:

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM