表A:
id  a   b   c    d    e
 1  1   3   5    3    2
 2  6   1   2    7    2
 3  3   1   1    1    1 大家好,请问在上面的表A中,我想找出各行中按字段a、b 、c、 d、 e顺序,依次相加,如果相加后的值大于6时,则将结果就取当前列名为结果。此SQL要怎样写?有没有分析函数支持?结时如下:
结果:
 id  result
  1     c
  2     a
  3     d

解决方案 »

  1.   


    with t as(
    select 1 id,1 a,3 b,5 c,3 d,2 e from dual
    union all
    select 2,6,1,2,7,2 from dual
    union all
    select 3,3,1,1,1,1 from dual
    )
    select id,
           COALESCE(case
                      when a >= 6 then
                       'a'
                    end,
                    case
                      when (a + b) >= 6 then
                       'b'
                    end,
                    case
                      when (a + b + c) >= 6 then
                       'c'
                    end,
                    case
                      when (a + b + c + d) >= 6 then
                       'd'
                    end,
                    case
                      when (a + b + c + d + e) >= 6 then
                       'e'
                    end) result
      from t
    也可以自己写个函数处理
      

  2.   

    select id,case when a>=6 then 'a'
    when a+b>=6 then 'b'
      when a+b+c>=6 then 'c'
        when  a+b+c+d>=6 then 'd'
          when a+b+c+d+e>=6 then 'e' end case  from A;
      

  3.   


    好算法没有,感觉用分析函数来完成这个功能反而更复杂了。--我是测试数据,请不要理我
    with t as (
    select 1 id,1 a,3 b,5 c,3 d,2 e from dual union all
    select 2, 6, 1, 2, 7, 2 from dual union all
    select 3, 3, 1, 1, 1, 1 from dual )-- 最后在累加值足够的列中取最小的列做为结果
    select distinct t_sum.id,first_value(colname) over(partition by id order by colname) result
    from
      -- 计算累加值并过滤掉累加值不足的记录
      (select id,colname,colvalue,sum(colvalue) over(partition by id order by colname) colsum 
      from
        -- 列转行
        (select id,'A' colname,a colvalue from t union all
        select id,'B' colname,B colvalue from t union all
        select id,'C' colname,C colvalue from t union all
        select id,'D' colname,D colvalue from t union all
        select id,'E' colname,E colvalue from t 
        ) t_col
      ) t_sum
    where colsum >= 6