zoukankan      html  css  js  c++  java
  • sql case 函数与详细说明

    下面是一个是用case函数来完成这个功能的例子

    case具有两种格式。简单case函数和case搜索函数。 
    --简单case函数

    case sex
             when '1' then '男'
             when '2' then '女'
    else '其他' end
    --case搜索函数
    case when sex = '1' then '男'
             when sex = '2' then '女'
    else '其他' end

    这两种方式,可以实现相同的功能。简单case函数的写法相对比较简洁,但是和case搜索函数相比,功能方面会有些限制,比如写判断式。 
    还有一个需要注意的问题,case函数只返回第一个符合条件的值,剩下的case部分将会被自动忽略。 
    --比如说,下面这段sql,你永远无法得到“第二类”这个结果

    case when col_1 in ( 'a', 'b') then '第一类'
             when col_1 in ('a')       then '第二类'
    else'其他' end


    下面看一些实例

    select country, 
    sum( case when sex = '1' then 
    population else 0 end), --男性人口 
    sum( case when sex = '2' then 
    population else 0 end) --女性人口 
    from table_a 
    group by country;


    select sum(population), 
    case country 
    when '中国' then '亚洲' 
    when '印度' then '亚洲' 
    when '日本' then '亚洲' 
    when '美国' then '北美洲' 
    when '加拿大' then '北美洲' 
    when '墨西哥' then '北美洲' 
    else '其他' end 
    from table_a 
    group by case country 
    when '中国' then '亚洲' 
    when '印度' then '亚洲' 
    when '日本' then '亚洲' 
    when '美国' then '北美洲' 
    when '加拿大' then '北美洲' 
    when '墨西哥' then '北美洲' 
    else '其他' end;

    关于case 二

    select 
    case when salary <= 500 then '1' 
    when salary > 500 and salary <= 600 then '2' 
    when salary > 600 and salary <= 800 then '3' 
    when salary > 800 and salary <= 1000 then '4' 
    else null end salary_class, 
    count(*) 
    from table_a 
    group by 
    case when salary <= 500 then '1' 
    when salary > 500 and salary <= 600 then '2' 
    when salary > 600 and salary <= 800 then '3' 
    when salary > 800 and salary <= 1000 then '4' 
    else null end;
    mysq中横表和纵表的转换有时也是用这种 方法来转换 http://blog.csdn.net/fysuccess/article/details/40789869

     case when 是静态的转换方法,肯定不适合大量动态数据的查询,新的查询方法如下  http://qianzhang.blog.51cto.com/317608/1202793

  • 相关阅读:
    主流的Nosql数据库的对比
    CCF考试真题题解
    排序
    2017-10-03-afternoon
    POJ——T 2728 Desert King
    51Nod——T 1686 第K大区间
    POJ——T 2976 Dropping tests
    2017-10-02-afternoon
    入参是小数的String,返回小数乘以100的String
    银联支付踩过的坑
  • 原文地址:https://www.cnblogs.com/xs-yqz/p/6420672.html
Copyright © 2011-2022 走看看