我有一个非常简单的问题。我正在使用Mysql工作台,我有一个类似下面的数据:
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子句和having子句之间的区别,我的语法应该有效。但是,系统告诉我"错误代码:1054。未知列' orderstatus'在'有条款'"这是有线的。
然而,当我像这样修改我的查询时:
select month(dateorderednew) as Month, sum(orders) as return_orders
from table_a
where orderstatus='returned
group by month;
它有效。
所以,这真的令人困惑。我认为有条款应遵循集团声明。但我不能回答为什么会发生这种情况?
你们对此有什么想法吗?
答案 0 :(得分:1)
在您的情况下,您应该使用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
。
答案 1 :(得分:1)
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
答案 2 :(得分:0)
您必须使用where子句替换 having子句中提到的条件。因为having clause filter the data on aggregated group
和where 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;
答案 3 :(得分:0)
'WHERE'子句对单个行值进行过滤...
where colname > 0
或
where colname = 'sometext'
“ HAVING子句”对行的组或集合进行过滤,如果有...,则在“ group by”语句之后。
group by colname
having count(*) > 0
或
group by colname
having sum(colname) < 1