select子句中case end和decode函数的使用 -电脑资料

电脑资料 时间:2019-01-01 我要投稿
【www.unjs.com - 电脑资料】

   

    如果要在Oracle数据库的select子句中实现字段值的大小比较,可以使用case end和decode函数实现,

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

    例如,查询出某个表的3个小时以上的处理统计数据,2个小时以内的处理统计数据,1个小时以内的处理统计数据的SQL语句。

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

    Sql代码

    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函数可以实现如下:

    Sql代码

    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

    使用case end可以直接得出比较值,大小一清二楚;而使用decode要使用sign可以一次转换,增加了一弯来绕,

电脑资料

select子句中case end和decode函数的使用》(https://www.unjs.com)。这是因为decode函数只能做等值比较。

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

最新文章