Oracle常用数据查询

一:decode的用法:
当你遇到 这样 的情形时候,可能会用到
1.第一种写法
你需要将学生成绩>=60的显示及格,小于60的显示不及格
select t.name,t.banji,decode(sign(t.chengji-60),-1,'不及格','及格')  from stu  t;
注:sign()是根据括号里的值是正数,负数,0,分别返回1,-1,0。
2.第二种写法
你需要将学生成绩>=90显示优秀,90>x>=80显示良好,80以下显示一般
select t.name,t.banji,
        decode(
                sign(t.chengji-90),1,'优秀',0,'优秀',-1,
                       decode(sign(t.chengji-80),1,'优秀',0,'优秀',-1, '一般' )
                    )  as score from stu t
也可以写成
select t.name,t.banji,
                decode(
                            sign(t.chengji-90),1,'优秀',0,'优秀',-1,
                                           decode(sign(t.chengji-80),1,'优秀',0,'优秀','一般' )
                                        )  as score from stu t
可以看出最后一种情况的判断值可以省略。

二:字符串拼接
当你查学生的名字的时候,你需要统一在名字前加上学校简称时候可以用‘||’
select ‘清华’ ||t.name  as stuName from stu t;
也可以select concat('清华',t.name)  as stuName from stu t;
当你需要把学生的名字,性别在一个字段显示时候
select '姓名:'||t.name||'性别:'t.sex as  msg from stu t;
在oracle中concat只能有两个参数,但我们可以用多个concat嵌套
select  concat(concat( concat('姓名:',t.name) ,'性别:'),t.sex) as msg from stu t;
三:nvl
当你查学生名字时候,如果有空值,要替换成‘未命名时’可用nvl
select nvl(t.name,'未命名') from stu t
例子:当我们查学生成绩时候,有时候成绩没有录入
select t.name ,t.banji,to_number(nvl(t.score,0)) as score from stu t ;
当我们仅查某个学生的成绩,这时候为了保证成绩肯定有值,可以加上sum
seleect nvl(sum(t.score),0)  as score from stu t where t.useId=11 ;
四:CASE WHEN THEN
当查询时,学生性别,为1显示男,为2显示女
select t.name,t.class,
(case  t.sex
     when  '1'  then '男'
     when ‘2’ then ‘女’
     else   '未设置'
  end )  as sex
from stu t;

当然也可以这样写
select t.name,t.class,
(case 
when  t.sex ='1'   then  '男'
when t.sex =‘2’   then  ‘女’
else    '未设置'
end )  as sex
from stu t;


用例
用例1:
  select count(1),
        sum(decode(t.product_type, '1', 1, 0)) as test1,
        sum(decode(t.product_type, '2', 1, 0)) as test2,
        sum(decode(t.product_type, '3', 1, 0)) as test3,
        sum(decode(t.product_type, '4', 1, 0)) as test4,
        sum(decode(t.product_type, '5', 1, 0)) as test5,
        sum(nvl2(t.product_type, 0, 1)) as test6
   from gq_base_invest t
统计各种类型的条目数(nvl2 如果为null 返回后面一个,不为null返回第一个值)。
select count(case t.product_type
                when '1' then
                 1
                else
                 null
              end) as test1,
        count(case t.product_type
                when '2' then
                 1
                else
                 null
              end) as test2,
       
        count(case t.product_type
                when '3' then
                 1
                else
                 null
              end) as test3
   from gq_base_invest t

用例2:
    select count(product_type),
        sum(nvl2(t.product_type, 0, 1)) as test6,
        count(*)
   from gq_base_invest t
count 某个字段时候,去空不去重复。

posted @ 2013-02-04 09:49  罗曼松松  Views(163)  Comments(0)    收藏  举报