当字段G = '0'时,group by a
当字段G = '1'时,group by b
当字段G = '2'时,group by a,b
当字段G = '3'时,group by c用case when好像不可以,
应该怎么实现?

解决方案 »

  1.   

    declare @s varchar2(4000);@s := 'select ...';if g = '0' then
       @s := @s||' group by a';
    end if;if g = '1' then
       @s := @s||' group by b';
    end if;if g = '2' then
       @s := @s||' group by a,b';
    end if;if g = '3' then
       @s := @s||' group by c';
    end if;open cur for @s;
      

  2.   

    对这个例子来说
    group 后的case 需要写两个
    并且由于分组的对象不确定,所有查询字段都需要聚合
    例如
    select max(a),max(b),max(c),max(g),count(1)
    from test
    group by case g when 0 then a when 1 then b when 2 then a when 3 then c end,
      case g when 2 then b end;
      

  3.   

    就像5楼说的那样,group by 要根据页面 传递的值,来确定那个分组
      

  4.   

    这样写,不对吧,我开始就是这样用case when 写的,
      

  5.   

    字段 G的值在一次SQL查询中固定吗?还有Group函数是sum,count还是其他Group函数?
      

  6.   

    有错误的话就是你的列没聚合好
    或者你case后用了when g='2' then a,b ?
      

  7.   

    就是有when g='2' then a,b 这样的
      

  8.   

    你看我上面写的代码group后面有什么不一样,有两个CASE
    你那么写会有语法错误
      

  9.   

    可能按几个参数分组就要写几个case
      

  10.   

    lz还是把你的数据给个例子吧,这样的统计不知道有什么用的具体应用。把数据的例子贴出来,你期望的结果也贴出来,毕竟是sql语句,除了要没有错,还要出来的数据正确。
      

  11.   

    我也不知道,怎么说我的目的就是对费用表中的应收人民币(cny),应收美金(usd)等金额进行分组统计,分组统计的条件就是根据页面传递的参数,来判断根据那个字段分组表的话,我不会建临时表,项目中的表也太复杂,不好拿出来
      

  12.   

    case when确实可以放到group by里对于你这样的统计,字段有变化的,会把所有的group的不同的值都列在这里,这样有意义吗。
      

  13.   


    select sum(case G when '1' then colUSD when '2' then colCNY end) 应收数
    from tablename
    group by case G when '1' then colA when '2' then colB end
      

  14.   

    如果Group By两个栏位的话就要两个Case When。
    case G when '2' then colC end