使用oracle with clause进行分组

时间:2017-05-03 03:29:00

标签: sql oracle

我有一张表,我试图通过年龄组和得分组来提取频率分布。以下是我正在运行的查询。

   with age_map as (select distinct age,case when age is not null 
                                        and AGE>=16 AND AGE<36 then '16-35'
                                      when age is not null and  AGE>=36 AND 
                                      AGE<56  then '36-56'
                                      when age is not null and  AGE>=56 then 
                                      '56+'
                                      when age is null then 'NA'
                                  end as age_group
                     from rec_table
                     where monthofsale = 'Apr 2017'
                      )
      select name,location,b.age_group,sum(weight),count(*)
      from rec_table a, age_map b
      where a.age = b.age
      group by name,location,b.age_group

运行查询时,我不断收到错误: ORA-00979:不是GROUP BY表达式

我很确定我要包含所有列。那么,想知道这是不是正确吗?

我的预期输出是:

      Name     location    age_group   weight count
       x          y         16-35         15   3
       p          q         36-56         48   7

有关于此的任何想法吗?

1 个答案:

答案 0 :(得分:0)

错误分组来自with子句:

选择如下:

select age, case when age is not null and AGE>=16 AND AGE<36 then '16-35'
                 when age is not null and  AGE>=36 AND AGE<56  then '36-56'
                 when age is not null and  AGE>=56 then  '56+'
                 when age is null then 'NA'
                 end as age_group
from rec_table
where monthofsale = 'Apr 2017'
group by age, case when age is not null and AGE>=16 AND AGE<36 then '16-35'
                 when age is not null and  AGE>=36 AND AGE<56  then '36-56'
                 when age is not null and  AGE>=56 then  '56+'
                 when age is null then 'NA'
                 end