MySQL:计算每天的不同行数,包括0

时间:2014-09-15 07:55:25

标签: mysql distinct

这里有一个很好的答案:MySQL: Count the distinct rows per day

我需要包含值的日子,但查询

SELECT  DATE(timestamp) Date, COUNT(DISTINCT ipNum) totalCOunt
FROM    tableName
WHERE totalCOunt < 1
GROUP   BY  DATE(timestamp)

给出错误(#1064 - 您的SQL语法中有错误;请查看与您的MySQL服务器版本对应的手册,以获得正确的语法,以便在&#39; WHERE totalCOunt&lt; 1附近使用 限制0,25和#39;在第3行)。我哪里出错了?

此处的示例数据:http://sqlfiddle.com/#!2/11aa6/146

3 个答案:

答案 0 :(得分:1)

您有一些错误:

  1. Date应该被转义,因为它是MySQL中的关键字。
  2. 语法错误。你忘记了AS
  3. 所以纠正的是:

    SELECT  CAST(`timestamp` AS Date) AS `Date`, COUNT(DISTINCT(`ipNum`)) AS totalCOunt
    FROM    `tableName`
    GROUP   BY CAST(`timestamp` AS Date)
    

    小提琴:http://sqlfiddle.com/#!2/809838/8

答案 1 :(得分:1)

在'where子句'错误中抛出未知列'totalCOunt':

请尝试以下查询(用HAVING子句替换WHERE子句):

SELECT  DATE(timestamp) Date, COUNT(DISTINCT ipNum) totalCOunt
FROM    tableName

GROUP   BY  DATE(timestamp)
HAVING totalCOunt<1

答案 2 :(得分:0)

您不能在WHERE子句中使用别名

SELECT  DATE(timestamp) Date, COUNT(DISTINCT ipNum) totalCOunt
FROM    tableName
WHERE totalCOunt < 1
GROUP   BY  DATE(timestamp)

改为使用HAVING:

SELECT  DATE(timestamp) Date, COUNT(DISTINCT ipNum) totalCOunt
FROM    tableName
GROUP   BY  DATE(timestamp)
HAVING totalCOunt =1