zoukankan      html  css  js  c++  java
  • 数据库练习2

    1、子查询的用法(也可实现分组求最大值)

    ALL的用法(很常用)

    1)在每一个州中找出最大面积的国家,列出洲份 continent, 国家名字 name 及面积 area。 (有些国家的记录中,AREA是NULL,没有填入资料的。)

    数据库world表:

    namecontinentareapopulationgdpcapitaltldflag
    Afghanistan Asia 652230 25500100 20364000000 Kabul .af //upload.wikimedia.org/wikipedia/commons/9/9a/Flag_of_Afghanistan.svg
    Albania Europe 28748 2821977 12044000000 Tirana .al //upload.wikimedia.org/wikipedia/commons/3/36/Flag_of_Albania.svg
    Algeria Africa 2381741 38700000 207021000000 Algiers .dz //upload.wikimedia.org/wikipedia/commons/7/77/Flag_of_Algeria.svg
    Andorra Europe 468 76098 3222000000 Andorra la Vella .ad //upload.wikimedia.org/wikipedia/commons/1/19/Flag_of_Andorra.svg

                ...

    分析area中含有null值,若不含null值,sql中可采用row_number() over(partition by ) 分组排序实现.

    代码:

    select a.name, a.continent , a,area from 
    (select name ,continent ,area ,
    row_number() over(partition by continent order by area desc) rank
    from world ) a 
    where a.rank =1
    

     area 中含有null值,采用子查询的方式:(2个表比较实现查询结果:比较条件区域相同,比较a的面积大于b的面积,区域下的所有其他项,引入all函数).

    select continent ,name, area from world a 
    where a.area >=
    all(select area from world b where a.continent = b.continent and b.area >0)
    

    2)找出洲份,当中全部国家都有少于或等于 25000000 人口. 在这些洲份中,列出国家名字name,continent 洲份和population人口。

    select name, continent ,population from world   a
    where 25000000 >  all(
    select b.population from world b 
    where a.continent  = b.continent and b.population >0
    ) 
    

    3) 有些国家的人口是同洲份的所有其他国的3倍或以上。列出 国家名字name 和 洲份 continent。

    select name,continent from world a 
    where a.population/3 >= all(
    select b.population  from world b 
    where a.continent = b.continent and b.population >0 and a.name <> b.name 
    )
    

    4)列出有至少100百萬(1億)(100,000,000)人口的洲份。

    select distinct(continent) from world a
    where 100000000 <= all(
    select sum(b.population ) from world b where a.continent = b.continent
    ) 
    
    # 第二种 group by ..having ..
    select continent  from (
    select continent ,sum(population ) from world 
    group by continent 
    having sum(population ) >= 100000000  )a 
    

      

    二、coalesce函数

    与null有关的函数,填充第一个不是null的值,若都没有值结果为null

      COALESCE(x,y,z) = x if x is not NULL
      COALESCE(x,y,z) = y if x is NULL and y is not NULL
      COALESCE(x,y,z) = z if x and y are NULL but z is not NULL
      COALESCE(x,y,z) = NULL if x and y and z are all NULL
    

      

  • 相关阅读:
    Markdown引用图片,且不使用网上链接的解决方法
    测试
    sudo用户权限添加问题
    windows安装ipython
    ansible基本操作
    mysql用户权限操作
    解决windows7系统的快捷方式无法添加到任务栏
    linux下查看磁盘分区的文件系统格式
    mail客户端POP和IMAP协议
    linux设置history历史记录
  • 原文地址:https://www.cnblogs.com/hqczsh/p/11721465.html
Copyright © 2011-2022 走看看