繁体   English   中英

具有从句和where子句的问题

[英]Questions for having clause and where clause

我有一个非常简单的问题。 我正在使用Mysql Bench,并且有如下数据:

dateordered_new        orderstatus  orders
2016-06-23 23:19:23     returned       8
2016-06-01 23:19:23     completed     12
2016-06-22 23:19:23     returned       9
2016-06-04 23:19:23     completed     27
...etc...

问题很简单,我想显示每个月已退回的订单数量。

这是我的查询:

select month(dateorderednew) as Month, sum(orders) as return_orders
from table_a
group by month
having orderstatus='returned;

考虑到where子句和Have子句之间的差异,应该使用我的语法。 但是,系统告诉我“错误代码:1054。'具有'子句'的未知列'orderstatus'”且已连接。

但是,当我这样修改查询时:

select month(dateorderednew) as Month, sum(orders) as return_orders
from table_a
where orderstatus='returned
group by month;

而且有效。

因此,这确实令人困惑。 我认为,有条文应以逐句方式跟在后面。 但是我无法回答为什么发生这种情况?

你们对此有什么想法吗?

在您的情况下,应使用where子句:

select month(dateorderednew) as Month, sum(orders) as return_orders
from table_a
where orderstatus='returned'
group by month

因为您要汇总之前从表中过滤掉行。

仅当您要对汇总值进行过滤时才使用having子句,例如

select month(dateorderednew) as Month, sum(orders) as return_orders
from table_a
group by month
having sum(orders) > 10

然而,MySQL的是灵活的,允许你使用一个having上非集合值。

HAVING用于过滤聚合结果,例如MIN/MAX/AVERAGE ,而WHERE用于过滤非聚合列。

例如,您可以这样做:

select month(dateorderednew) as Month, sum(orders) as return_orders
from table_a
WHERE orderstatus='returned'
group by month
having sum(orders) < 100

您必须将where子句中提到的条件替换为where子句 因为having clause filter the data on aggregated groupwhere clause filter the data on whole record set

试试下面的SQL:

Select month(dateorderednew) as Month, sum(orders) as return_orders
from table_a
where orderstatus='returned
group by month;

'WHERE'子句过滤单个行值...

where colname > 0

where colname = 'sometext'

'HAVING子句在行的组或集合上进行过滤,如果有一个,则在'group by'语句之后...

group by colname
having count(*) > 0

要么

group by colname   
having sum(colname) < 1

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM