zoukankan      html  css  js  c++  java
  • 《SQL 进阶教程》 case:将已有编号方式转换为新的方式并统计

    SQL 权威指南
    SQL 解惑
    在进行非定制化统计时,需要将已有编号方式转换为另外一种便于分析的方式进行统计需求

    select
    case
    when name='哈尔滨' then '黑龙江'
    when name='大庆' then '黑龙江'
    when name='齐齐哈尔' then '黑龙江'
    when name='长春' then '吉林'
    when name='吉林' then '吉林'
    when name='沈阳' then '辽宁'
    when name='大连' then '辽宁'
    when name='葫芦岛' then '辽宁'
    else '其他'
    end as province,sum(population)
    from city_population
    GROUP BY
    case
    when name='哈尔滨' then '黑龙江'
    when name='大庆' then '黑龙江'
    when name='齐齐哈尔' then '黑龙江'
    when name='长春' then '吉林'
    when name='吉林' then '吉林'
    when name='沈阳' then '辽宁'
    when name='大连' then '辽宁'
    when name='葫芦岛' then '辽宁'
    else '其他' end


    select
    case
    when name='哈尔滨' then '黑龙江'
    when name='大庆' then '黑龙江'
    when name='齐齐哈尔' then '黑龙江'
    when name='长春' then '吉林'
    when name='吉林' then '吉林'
    when name='沈阳' then '辽宁'
    when name='大连' then '辽宁'
    when name='葫芦岛' then '辽宁'
    else '其他'
    end as province,sum(population)
    from city_population
    group by province

    严格来说,这种写法违反标准sql规范,因为Group by 比select 语句先知,
    所以group by 子句中引用在select 子句里定义的别称是不被允许的,
    事实上,在oracle、DB2、SQLServer 等数据库采用这种写法时就会出错


    将人口按照适当的级别进行分类统计
    select
    case
    when population < 100 then '1'
    when population >=100 and population <200 then '2'
    when population >=200 and population < 400 then '3'
    else '4' end as pop_class,count(*) as cnt
    from city_population
    GROUP BY pop_class

  • 相关阅读:
    3D 服务器端以向量计算为主的角色位置的算法
    宇宙中可见物质为 4%,暗物质和暗能量占 96% 是怎么算出来的?
    量子纠缠
    “人的第一感觉(直觉)其实非常准”
    有哪些看似荒谬,其实很科学的理论@知乎、@量子力学
    CPU/寄存器/内存
    原子操作
    简单的介绍下WPF中的MVVM框架
    IOS开发中,TextField和TextView有何区别
    年后小结
  • 原文地址:https://www.cnblogs.com/newlangwen/p/10541034.html
Copyright © 2011-2022 走看看