选择不同,同时按小时分组

时间:2014-05-07 19:54:37

标签: mysql count group-by distinct

我有这个查询,但是当我指定一个不同的计数时,它无法正常工作。我知道语法必须在某个地方关闭,但我不知所措。

按小时准确计算的查询组是:

SELECT HOUR(dateAdded)  AS Hour,
       COUNT(dateAdded) AS `user_count`
FROM   Track
WHERE  dateAdded BETWEEN '2014-04-01' AND '2014-05-02'
        OR dateAdded IS NULL
GROUP  BY HOUR(dateAdded)
ORDER  BY Hour  

具有不同计数调整的新陈述如下:

SELECT HOUR(dateAdded)                           AS Hour,
       COUNT(DISTINCT remoteAddr, xForwardedFor) AS `user_count`
FROM   Track
WHERE  dateAdded BETWEEN '2014-05-01' AND '2014-05-02'
        OR dateAdded IS NULL
           AND accessMask = '1iczo'
GROUP  BY HOUR(dateAdded)
ORDER  BY Hour  

我知道这可能是抽象的而不参考实际数据,如果你需要它我可以更新问题以供参考。

更新 发布的答案使我在思考解决方案方面朝着正确的方向发展,但我不相信它会返回准确的结果。我想出了这个解决方案,以防它对其他人有用,发布了。这可能会做得更好,但我能够提出并给出准确的结果。

SELECT HOUR( dateAdded ) AS HOUR , COUNT( DISTINCT remoteAddr, xForwardedFor ) AS cnt
FROM Track
WHERE accessMask =  '1iczo'
AND destination =  'lp_include.php'
AND dateAdded
BETWEEN  '2014-05-01'
AND  '2014-05-02'
GROUP BY HOUR
ORDER BY HOUR

1 个答案:

答案 0 :(得分:0)

我认为你应该用子查询来做到这一点

不要以为你不能在两列上做count(distinct ...)

SELECT hour, count(*) as user_count
from
   (SELECT HOUR(dateAdded) AS Hour,
           remoteAddr, 
           xForwardedFor

    FROM   Track
    WHERE  dateAdded BETWEEN '2014-05-01' AND '2014-05-02'
        OR dateAdded IS NULL
           AND accessMask = '1iczo'
    GROUP  BY HOUR(dateAdded), remoteAddr, xForwardedFor) s
group by hour
order by hour