MySQL group by和Where

时间:2012-11-02 18:49:32

标签: mysql group-by where

我想在下面的sql中添加一个where子句,以便名为“howmany”的列只显示大于1的结果,但是当我尝试时我一直收到错误。

 select monthname(birthdate) as 'Month', Count(*) as howmany
 from tblBday
 group by month(birthdate)
 ;

5 个答案:

答案 0 :(得分:1)

您不能在WHERE子句中使用别名,并且由于您想使用聚合函数,因此您需要HAVING子句:

select monthname(birthdate) as `Month`, Count(*) as howmany
from tblBday
group by month(birthdate)
having Count(*) > 1

如果想在WHERE子句中使用别名,则可以将查询作为子查询:

select `month`, howmany
from
(
    select monthname(birthdate) as `Month`, Count(*) as howmany
    from tblBday
    group by month(birthdate)
) src
where howmany > 1

答案 1 :(得分:1)

这是因为你不能在WHERE子句中使用别名

此外,您不能在WHERE子句中执行聚合函数

你需要这样的东西

SELECT monthname(birthdate) as Month, Count(*) AS howmany
FROM tblBday
GROUP BY month(birthdate)
HAVING Count(*) > 1
 ;

Here's关于HAVING的tuto

答案 2 :(得分:1)

 select monthname(birthdate) as 'Month', Count(*) as howmany
                                ^--   ^--

你不能引用这样的别名。单引号(')将事物转换为字符串 - 字符串不是别名,也不能是别名。删除引号,或使用反引号:

select monthname(birthdate) as Month, Count(*) as howmany

答案 3 :(得分:0)

尝试

select monthname(birthdate) as 'Month', Count(*) as howmany
from tblBday
group by month(birthdate)
having howmany > 1
;

答案 4 :(得分:0)

 select monthname(birthdate) as 'Month', Count(*) as howmany
 from tblBday
 group by monthname(birthdate)
Having count(*) > 1
;