`
mikixiyou
  • 浏览: 1084747 次
  • 性别: Icon_minigender_1
  • 来自: 南京
博客专栏
C3c8d188-c0ab-3396-821d-b68331e21226
Oracle管理和开发
浏览量:348970
社区版块
存档分类
最新评论

select子句中case end和decode函数的使用

阅读更多

如果要在Oracle数据库的select子句中实现字段值的大小比较,可以使用case end和decode函数实现。
例如,查询出某个表的3个小时以上的处理统计数据,2个小时以内的处理统计数据,1个小时以内的处理统计数据的SQL语句。

使用case end函数可以实现如下:

select t.custommgrid,
       count(case
               when (t.createtime - t.firstdealtime) >= 3 / 24 then
                t.dealflag
               else
                null
             end) as threehour_things,
       count(case
               when (t.createtime - t.firstdealtime) < 2 / 24 then
                t.dealflag
               else
                null
             end) as twohour_things,
       count(case
               when (t.createtime - t.firstdealtime) < 1 / 24 then
                t.dealflag
               else
                null
             end) as onehour_things,
       count(t.dealflag) as all_things
  from tb_name t
 where t.dealflag = 1
 group by t.custommgrid;

 
使用decode函数可以实现如下:

select count(decode(sign((t.createtime - t.firstdealtime) - 3 / 24),
                    -1,
                    null,
                    t.dealflag)) as threehour_things,
       count(decode(sign((t.createtime - t.firstdealtime) - 2 / 24),
                    -1,
                    t.dealflag,
                    null)) as twohour_things,
       count(decode(sign((t.createtime - t.firstdealtime) - 1 / 24),
                    -1,
                    t.dealflag,
                    null)) as onehour_things,
       count(t.dealflag) as all_things
  from tb_name t
 where t.dealflag = 1
 group by t.custommgrid;

 

 decode(条件,值1,翻译值1,值2,翻译值2,...值n,翻译值n,缺省值)
  该函数的实现逻辑是这样:
  IF 条件=值1 THEN
  RETURN(翻译值1)
  ELSIF 条件=值2 THEN
  RETURN(翻译值2)  ......
  ELSIF 条件=值n THEN
  RETURN(翻译值n)
  ELSE
  RETURN(缺省值)
  END IF

 

(miki西游 @mikixiyou 原文链接: http://mikixiyou.iteye.com/blog/1716817 )


使用case end可以直接得出比较值,大小一清二楚;而使用decode要使用sign可以一次转换,增加了一弯来绕。这是因为decode函数只能做等值比较。

因此,对于此类需求,最好还是使用case end来实现。

 

 

 

分享到:
评论
1 楼 jz20110918 2013-03-22  
一直保留着看帖回复的良好习惯,所以看完此贴总结,感觉很有裨益。

相关推荐

Global site tag (gtag.js) - Google Analytics