zoukankan      html  css  js  c++  java
  • SQL语句中having的用法

    在 SQL 中增加 HAVING 子句原因是,WHERE 关键字无法与合计函数一起使用。

    having子句用法一(来自w3school):

    SQL HAVING 语法如下

    SELECT column_name, aggregate_function(column_name)
    FROM table_name
    WHERE column_name operator value
    GROUP BY column_name
    HAVING aggregate_function(column_name) operator value
    

    SQL HAVING 实例

    我们拥有下面这个 "Orders" 表:

    O_IdOrderDateOrderPriceCustomer
    1 2008/12/29 1000 Bush
    2 2008/11/23 1600 Carter
    3 2008/10/05 700 Bush
    4 2008/09/28 300 Bush
    5 2008/08/06 2000 Adams
    6 2008/07/21 100 Carter

    现在,我们希望查找订单总金额少于 2000 的客户。

    我们使用如下 SQL 语句:

    SELECT Customer,SUM(OrderPrice) FROM Orders
    GROUP BY Customer
    HAVING SUM(OrderPrice)<2000
    

    结果集类似:

    CustomerSUM(OrderPrice)
    Carter 1700

    现在我们希望查找客户 "Bush" 或 "Adams" 拥有超过 1500 的订单总金额。

    我们在 SQL 语句中增加了一个普通的 WHERE 子句:

    SELECT Customer,SUM(OrderPrice) FROM Orders
    WHERE Customer='Bush' OR Customer='Adams'
    GROUP BY Customer
    HAVING SUM(OrderPrice)>1500
    

    结果集:

    CustomerSUM(OrderPrice)
    Bush 2000
    Adams 2000


    SQL having子句用法二:

    查询表中某字段个数

    O_IdOrderDateOrderPriceCustomer
    1 2008/12/29 1000 Bush
    2 2008/11/23 1600 Carter
    3 2008/10/05 700 Bush
    4 2008/09/28 300 Bush
    5 2008/08/06 2000 Adams
    6 2008/07/21 100 Carter

    select *, count(Customer) as a from Orders group by Customer having a>1
  • 相关阅读:
    Linux环境下安装python3
    软件测试类型
    系统测试分类
    测试级别
    测试对象的介绍
    软件测试基本介绍
    简易留言板(还有一些小bug,修复ing...)
    Hosting static website on AWS
    Add a dependency in Android Studio
    Python good tutorials
  • 原文地址:https://www.cnblogs.com/joewu/p/3938627.html
Copyright © 2011-2022 走看看