最近工作中遇到数据库的问题,本人ORACLE不精,来问下大家。表中有字段A和字段,A有0,1,2,3这几种情况的值,如何做到:
1 在A全为0的情况,B设为01,A不全为0的情况,B设为02;
2 在A部分为2的情况,B设为03,A全不为2的情况,B设为03;
问题大致是这样,要在一条SQL文中完成以上功能,因为后台是JAVA,所以要求
能够嵌入JAVA。听说CASE和OVER可以实现,但不知道具体如何实现。

解决方案 »

  1.   

    请列出的表中的记录数据,和最终达到结果的记录数据
    最好的sql脚本如
    create table t
    insert into t values...
    insert into t values...这样其它人才可能快速回复你
      

  2.   

    [code=SQL]--建表
    create table t (a number);
    --插入两条测试数据
    insert into t values(0);
    insert into t values(0);
    --测试语句
    select case
             when (select count(1) from t where t.a = 0) =
                  (select count(1) from t) then
              '01'
             when (select count(1) from t where t.a = 0) <>
                  (select count(1) from t) then
              '02'
             when (select count(1) from t where t.a = 2) <>
                  (select count(1) from t) then
              '03'
             when (select count(1) from t where t.a = 2) = 0 then
              '04'
             else
              null
           end as b
      from dual;code]
      

  3.   


    --建表 
    create table t (a number); 
    --插入两条测试数据 
    insert into t values(0); 
    insert into t values(0); 
    --测试语句 
    select case 
            when (select count(1) from t where t.a = 0) = 
                  (select count(1) from t) then 
              '01' 
            when (select count(1) from t where t.a = 0) <> 
                  (select count(1) from t) then 
              '02' 
            when (select count(1) from t where t.a = 2) <> 
                  (select count(1) from t) then 
              '03' 
            when (select count(1) from t where t.a = 2) = 0 then 
              '04' 
            else 
              null 
          end as b 
      from dual;
      

  4.   

    改成这样对吗?
     2 在A部分为2的情况,B设为03,A全不为2的情况,B设为04;还有一个问题是觉得02和03有些冲突.以下是根据我自己的理解写的代码,仅供参考:
      UPDATE t
         SET b = decode((select count(1) from t where a <> 0), 0, '01',
                          decode((select count(1) from t where a = 2), 0, '04', '03'));