我想在下面的 sql 中添加一个 where 子句,以便名为“howmany”的列只显示大于 1 的结果,但是当我尝试时我不断收到错误消息。
select monthname(birthdate) as 'Month', Count(*) as howmany
from tblBday
group by month(birthdate)
;
您不能在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
这是因为您不能在 WHERE 子句中使用别名
此外,您不能在 WHERE 子句中执行聚合函数
你需要这样的东西
SELECT monthname(birthdate) as Month, Count(*) AS howmany
FROM tblBday
GROUP BY month(birthdate)
HAVING Count(*) > 1
;
这是关于 HAVING 的教程
select monthname(birthdate) as 'Month', Count(*) as howmany
^-- ^--
你不能像那样引用别名。单引号 ( '
) 将事物转换为字符串 - 字符串不是别名,也不能是别名。删除引号,或使用反引号:
select monthname(birthdate) as Month, Count(*) as howmany
尝试
select monthname(birthdate) as 'Month', Count(*) as howmany
from tblBday
group by month(birthdate)
having howmany > 1
;
select monthname(birthdate) as 'Month', Count(*) as howmany
from tblBday
group by monthname(birthdate)
Having count(*) > 1
;