想请教一个问题:一个select 语句中必须要group by a字段,于是有
select
max(b),
max(c),
max(d),
...,
a
from table
group by a现在要再加一个字段,该字段是sum一个字段,单该字段 不能 group by a,而必须group by c,那这个SQL该怎么写呢??

解决方案 »

  1.   

    可以a、c一起分组吗? group by (a,c);
      

  2.   

    分别group by,得到两个数据,然后对这两个数据做嵌套关联查询
      

  3.   

    a,c非同一字段,分组出来的数据行可能不同,不能同时max group by a,sum又group by c。
    要么写成两个语句然后再根据条件关联。
      

  4.   

    1
    要么单独sum 在关联2
    这样
    sum(字段) over(order by 1)
      

  5.   


    --对你group by a的结果集在外面嵌套一层,以分析函数c 分组,如:
    select a,b,c,d....sum(字段)over(partition by c) from(
         select
            max(b) b,
            max(c) c,
            max(d) d,
            ...,
            a
         from table
         group by a
    )
      

  6.   

    select max(b),max() ,.., sum_c
    from table
    left join
    (
    select sum() sum_c
    from   table
    group by c
    )
    on 条件
    where 条件
    group by a
      

  7.   

    你这个需求逻辑有问题 ,你再详细的看下需求吧  既然你原使用group a 也分组的 ,那么如果你想得到group c的数据 ,你即使能得到数据 ,但是你怎么对应呢 ,和group a的数据每行都对应不起来 ,没有规则
      

  8.   

    有数据 a        b        c      d
    1        3        3      3
    1        8        2      2
    2        7        3      2
    2        10       3      11这是 你group a  ,max(b) max(d) 结果
    a    maxb maxd
    1         8     3
    2         10    11那么你如果现要按照 group c求 sum(b) ,sum(d) 结果
    c        sum(b) sum(d)
    2         8       2
    3         20      16 这2个结果集 怎么也联系不到一起啊,呵呵
      

  9.   

    sum()over(partition by ..order by ..)
      

  10.   

    Oracle 9i版本以上,有个 grouping sets 函数的,看能不能满足你的需求:
    select a,c,max(a),sum(c) from table group by grouping sets(a,c);
      

  11.   

    试试 grouping sets(a,c) 
      

  12.   

    其实我是用来做报表的,用14楼的例子:有数据  a b c d
    1 3 3 3
    1 8 2 2
    2 7 3 2
    2 10 3 11这是 你group a ,max(b) max(d) 结果
    a maxb maxd
    1   8     3
    2   10    11
    然后我还需要一个总计字段,sum(b),由于是总和所以不能group by a,得出的结果是:
    a maxb maxd   sum(b)
    1   8     3       28
    2   10    11      28虽然逻辑上有点说不过去,但是我只是想知道有没有这种写法??个人见解:
    这种情况可能用个union可以解决:a,max(b) b,max(c)c ''d group by a
    union
    '' a, ''b, ''c sum(b) d
    但是要union的字段如果多了岂不是很麻烦,所以有以上这个问题
      

  13.   

    有函数可以做到,rollup还是grouping来着.没用过,gelyon好像会用