标签:ali cti creat reg rod 计算 from 多重 having
视图的优点:
创建一个名为商品合计表的视图
CREATE VIEW ProductSum (product_type, cnt_product)
AS
SELECT product_type, COUNT(*)
    FROM Product
 GROUP BY product_type;创建视图之后可以使用简单的select语句查询。
使用DROP VIEW
视图之前上再创建视图,ProductSum为之前创建的视图
CREATE VIEW ProductSumJim (product_type, cnt_product)
AS
SELECT product_type, cnt_product
FROM ProductSum
WHERE product_type = '办公用品';    对多数DBMS来说,多重视图会降低SQL的性能,所以应该尽量避免创建多重视图。
有些视图可以跟新,但必须满足,select子句为单表,既没有聚合又没有结合的select语句
CREATE VIEW ProductJim (product_id, product_name, product_type, sale_price, purchase_price, regist_date)
AS 
SELECT *
    FROM Product
 WHERE product_type = '办公用品';-- 向视图插入数据(原表也插入了此条数据)
INSERT INTO ProductJim VALUES ('0009', '印章', '办公用品', 95, 10, '2009-11-30');执行顺序:内层的select子句——>外层的select子句
SELECT product_type, cnt_product
FROM (SELECT product_type, COUNT(*) AS cnt_product
                FROM Product
             GROUP BY product_type) AS ProductSum;注:为子查询设定名称时,需要使用AS关键字,该关键字有时也可以省略。
*不能在where子句中使用聚合函数(下面这句是会报错的!!!!)
SELECT * FROM product 
WHERE sale_price > AVG(sale_price);
> 1111 - Invalid use of group function计算平均销售单价的标量子查询(返回单一结果(一行一列))
 select avg(sale_price) from product;汇总:where中使用标量子查询
 SELECT * FROM product 
 WHERE sale_price > (select avg(sale_price) from product);注:标量子查询通常可以在任何使用单一值的位置都可以使用(select/group by/having...)
-- 标量子查询结束作为常数
SELECT product_id, 
       product_name, 
       sale_price,
       (SELECT AVG(sale_price) FROM Product) AS avg_price 
FROM Product;SELECT product_type, AVG(sale_price)
    FROM Product
 GROUP BY product_type
HAVING AVG(sale_price) > (SELECT AVG(sale_price) FROM Product);在细分的组内进行比较时,需要使用关联子查询
SELECT product_type, product_name, sale_price
    FROM Product AS P1
 WHERE sale_price > (SELECT AVG(sale_price) 
                       FROM Product AS P2 
                     WHERE P1.product_type = P2.product_type ROUP BY product_type);标签:ali cti creat reg rod 计算 from 多重 having
原文地址:https://www.cnblogs.com/sanzashu/p/11027401.html