zoukankan      html  css  js  c++  java
  • 分组与聚合数据

    GROUP BY子句,HAVING子句。

    聚合函数:COUNT();SUM();AVG();MAX();MIN().

    1.GROUP BY子句的应用

    select state from MemberDetails group by state;    --严格来说,select distinct也能完成这个任务。NULL值也能够被列出。
    
    select state from MemberDetails where state in('Mega State','Goldern State','New State') group by state;   --也可以包含一个where子句,必须放在group by之前

    select street,city,state from MemberDetails group by street,City,State;        --多个列的情况。列举出这3列的唯一组合

    select city,state from MemberDetails group by state;     --查询错误。因为city列没有包含在聚合函数或GROUP BY子句中

    2.汇总和聚合数据

    (1)COUNT()函数

    select count(*) from MemberDetails;
    select count(street) from MemberDetails;
    select count(city),count(state) from MemberDetails;
    select count(distinct CategoryId) from FavCategory;     --聚合函数中的distinct选项
    select city,count(LastName) from MemberDetails; --错误。city可能返回多行,但是count(city)只返回一行
    select state,count(lastname) from MemberDetails group by state;    --列举每类state中lastname列的数目

    (2)SUM()函数

    select sum(DVDPrice*1.1) from Films where AvailableOnDVD='Y' and DVDPrice<10;

    (3)AVG()函数

    select Category,AVG(DVDPrice) FROM Films inner join Category on films.CategoryId=Category.Category where AvailableOnDVD='Y' group by Category;

    (4)MAX(),MIN()函数

    select max(lastname),min(lastname) from MemberDetails where MemberDetails>3;

    3.HAVING子句和GROUP BY子句的综合应用

    HAVING子句是针对每个分组的,过滤掉了不匹配条件的分组。而WHERE子句是针对记录的,过滤掉了不匹配条件的记录。

    select Category,count(FavCategory.CategoryId) as popularity from FavCategory inner join Category on FavCategory.CategoryId=Category.CategoryId group by Category.Category
    having count(FavCategory.CategoryId)>3 order by popularity desc;     --仅列举那些被3个以上成员喜爱的电影的种类,并且按降序排列

  • 相关阅读:
    第4章:kubectl命令行管理工具
    Docker_CICD笔记
    Harbor镜像仓库
    centos7 安装最新的 wiki confluence
    Centos7.5使用SSH密钥登录
    一篇文章带你搞懂 etcd 3.5 的核心特性
    腾讯云边缘容器 TKE Edge 国内首批通过边缘容器技术能力认证
    揭秘有状态服务上 Kubernetes 的核心技术
    腾讯云云原生混合云-TKE发行版
    kubernetes 降本增效标准指南|理解弹性,应用弹性
  • 原文地址:https://www.cnblogs.com/wy1290939507/p/4532037.html
Copyright © 2011-2022 走看看