簡體   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