2

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

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

5 回答 5

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
于 2012-11-02T18:51:55.477 回答
1

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

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

你需要这样的东西

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

这是关于 HAVING 的教程

于 2012-11-02T18:52:05.287 回答
1
 select monthname(birthdate) as 'Month', Count(*) as howmany
                                ^--   ^--

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

select monthname(birthdate) as Month, Count(*) as howmany
于 2012-11-02T18:52:55.087 回答
0

尝试

select monthname(birthdate) as 'Month', Count(*) as howmany
from tblBday
group by month(birthdate)
having howmany > 1
;
于 2012-11-02T18:52:16.383 回答
0
 select monthname(birthdate) as 'Month', Count(*) as howmany
 from tblBday
 group by monthname(birthdate)
Having count(*) > 1
;
于 2012-11-02T18:53:28.690 回答