以一道题来做引子
牛客,SQL30 计算总和
OrderItems表代表订单信息,包括字段:订单号order_num和item_price商品售出价格、quantity商品数量。
| order_num | item_price | quantity | 
| a1 | 10 | 105 | 
| a2 | 1 | 1100 | 
| a3 | 1 | 200 | 
| a4 | 2 | 1121 | 
| a5 | 5 | 10 | 
| a6 | 1 | 19 | 
| a7 | 7 | 5 | 
【问题】编写 SQL 语句,根据订单号聚合,返回订单总价不小于1000 的所有订单号,最后的结果按订单号进行升序排序。
提示:总价 = item_price 乘以 quantity
| order_num | total_price | 
| a1 | 1050 | 
| a2 | 1319 | 
| a4 | 2242 | 
先来看一看错误的写法:
   
    - 
     
      
     
     
      
       select order_num, 
       sum(item_price*quantity) total_price
      
     
- 
     
      
     
     
      
       from OrderItems
      
     
- 
     
      
     
     
      
       group by order_num
      
     
- 
     
      
     
     
      
       where total_price >= 
       1000
      
     
- 
     
      
     
     
      
       order by order_num
      
     
错误:SQL_ERROR_INFO: "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'where total_price >= 1000\norder by order_num' at line 4"
上述的错误为:非法使用聚合函数,不能在 WHERE 子句中使用聚合函数
我们的 total_price等价于sum(item_price*quantity),而在WHERE 子句中使用聚合函数
改错
   
    - 
     
      
     
     
      
       select order_num, 
       sum(item_price*quantity) total_price
      
     
- 
     
      
     
     
      
       from OrderItems
      
     
- 
     
      
     
     
      
       group by order_num
      
     
- 
     
      
     
     
      
       having total_price >= 
       1000
      
     
- 
     
      
     
     
      
       order by order_num
      
     
这样就对了
使用having时注意:
1. 行已经被分组。
2. 使用了聚合函数。
3. 满足HAVING 子句中条件的分组将被显示。
4. HAVING 不能单独使用,必须要跟 GROUP BY 一起使用。
那么和where的区别有以下几点:
1. WHERE 可以直接使用表中的字段作为筛选条件,但不能使用分组中的计算函数作为筛选条件; HAVING 必须要与 GROUP BY 配合使用,可以把分组计算的函数和分组字段作为筛选条件。
2. 如果需要通过连接从关联表中获取需要的数据,WHERE 是先筛选后连接,而 HAVING 是先连接 后筛选。
3. 第二项导致了WHERE执行效率高,不能使用分组中的计算函数进行筛选,而HAVING 可以使用分组中的计算函数,执行效率较低。
转载:https://blog.csdn.net/fanfangyu/article/details/128596131
