• 超强:SQL命令中的case...when...then...else...end条件查询(不同于where) 与 类型转换的用法


    case...when...then...else...end,是在from前面,可以改变记录中某字段的值,不能决定是否显示该记录;

    where,是在from后面,不可以改变记录中某字段的值,但可以决定是否显示该记录。

    case...when...then...else...end,可用于对同一记录的多个字段求和,带分支判断。

    另外,对字段判断和处理,往往需要强制类型转换。

    select to_number(’19f’,’xxx’) from dual; --八进制
    得到  415
    select to_number(’f’,’xx’) from dual; --十六进制
    得到  15

    select to_number(’123’)  from dual; --十进制
    得到  123

    与date操作关系最大的就是两个转换函数:to_date(),to_char()
    to_date() 作用将字符类型按一定格式转化为日期类型:
    具体用法:to_date('2004-11-27','yyyy-mm-dd'),
    前者为字符串,后者为转换日期格式,注意,前后两者要以一对应。如to_date('2004-11-27 13:34:43', 'yyyy-mm-dd hh24:mi:ss') 将得到具体的时间

    字符串处理函数:

    select to_number(SUBSTR(rain_1,0,2),'xx')  from obs

    (一)Access 数据库

    大家知道在access中有iif函数,能将一个判断赋值序列简化成一个表达式,比如
    iif(a>b,1,2),如果确实a>b那么结果给出1,否则就是2。这实在很方便。

    示例
    (1)数字
    如果 Measures.CurrentMember 是空单元,则下面的示例返回 0,否则返回 1
    IIf(IsEmpty(Measures.CurrentMember), 0, 1)

    (2)字符串
    如果Measures.CurrentMember 是空单元,则下面的字符串返回字符串"Yes",否则返回字符串"No"
    IIf(IsEmpty(Measures.CurrentMember), "Yes", "No")

    在Access中我可以用IIF函数进行统计汇总,比如,要知道实际应该交费的用户个数
    Access写法:Select sum(iif(金额>0, 1,0)) as num from 费用

    MS SQL写法:select sum(case when 金额>0 then 1 else 0 end) as num from 费用

    (二)Ms SQL 数据库

    IIF在SQL中是 case when ....then ...else...  end

    例:select id,case when bz='1' then xx when bz='2' then yy else zz end as tt from xxx

    这里我举个例子,有一个表政策法规表(policy_fgxx),有ID(主键)、bzh(标准号)、zynr(主要内容)、

    fbrq(发布日期)四个字段

    Select * From policy_fgxx 结果:

    ID bzh zynr fbrq
    13 001 <p>你好</p> 2010-05-07 0:00:00
    15 NULL

     

    我不想要上面的结果,我想要下面这个结果:

    ID bzh zynr fbrq
    13 001 <p>你好</p> 2010-05-07 0:00:00
    15 无 1990-06-06 0:00:00

    也就是说,标准号为空的时候我想让它显示空,发布日期为null的时候我想让它显示我指定的日期

    下面我给出写法,大家可以自己思考

    Select id,zynr,
    (case when bzh='' then '无' else bzh end) AS bzh,
    (case when fbrq is null then '1982-06-02' else fbrq end) AS fbrq
    From policy_fgxx

     

    参考网址:

    http://blog.sina.com.cn/s/blog_659010f40100qtti.html

    http://zhidao.baidu.com/question/469795289.html

  • 相关阅读:
    iphone 低版本渲染不出来内容的一种解决办法
    win10 安装flutter记录
    ElasticSearch操作实例大全---文档结构操作(2)
    .net 实现word、excel、ppt、pdf预览功能
    layer插件弹出显示圆角
    ElasticSearch操作实例大全---文档结构操作(1)
    uploadify实战操作(一)
    mcDropdown使用方法
    用datatable 读写xml 及追加数据到xml
    百度分享
  • 原文地址:https://www.cnblogs.com/yuan2013/p/sqlcase.html
Copyright © 2020-2023  润新知