SQL - 按预期分组不分组

时间:2014-10-09 23:01:59

标签: sql oracle group-by

不提供有关表格结构和数据的详细信息:

原因可能是这个群体:

select c.state, case 
when age <20 then 'u20'
when (age >=20 and age<30 ) then 'o20'
when (age >=30 and age<40 ) then 'o30'
when (age >=40 and age<50 ) then 'o40'
else 'min50'
end age_group,
count(*) amount_trans, sum(t.SELLING_PRICE) sum_price from customers c, transactions t
where t.CUSTOMER_ID=c.CUSTOMER_NO
group by age, state
order by state, age

返回AGE_GROUP的多个条目,例如:

STATE       AGE_GROUP   AMOUNT_TRANS SUM_PRICE
Arizona     o30         26           667609
Arizona     o30         84           913807
Arizona     o30         34           161111
Arizona     min50       2            93791
Arizona     min50       3            907
California  u20         1            83048
California  u20         1            83048
California  o20         1            54772

可能的目标是:

STATE       AGE_GROUP   AMOUNT_TRANS SUM_PRICE
Arizona     o30         144          1742527
Arizona     min50       5            94698
California  u20         3            220868

是否有重复的行?

3 个答案:

答案 0 :(得分:2)

如果你想通过AGE_GROUP分组,你需要,呃,按AGE_GROUP分组。

select state,
       age_group,
       count(*) amount_trans,
       sum(t.SELLING_PRICE) sum_price  
from (  
    select c.state, 
            case 
               when age <20 then 'u20'
               when (age >=20 and age<30 ) then 'o20'
               when (age >=30 and age<40 ) then 'o30'
               when (age >=40 and age<50 ) then 'o40'
               else 'min50'
           end age_group,
           t.SELLING_PRICE
    from customers c, 
         transactions t
    where t.CUSTOMER_ID=c.CUSTOMER_NO
)
group by age_group, state
order by state, age_group

答案 1 :(得分:1)

因为你按年龄,州分组。 你的意思是按年龄组分组,状态?

答案 2 :(得分:1)

更改为:

select      c.state,
            case 
                when age <20 then 'u20'
                when (age >=20 and age<30 ) then 'o20'
                when (age >=30 and age<40 ) then 'o30'
                when (age >=40 and age<50 ) then 'o40'
                else 'min50'
                    end age_group,
            count(*) amount_trans,
            sum(t.SELLING_PRICE) sum_price
from        customers c
       join transactions t
         on t.CUSTOMER_ID = c.CUSTOMER_NO
group by    c.state,
            case 
                when age <20 then 'u20'
                when (age >=20 and age<30 ) then 'o20'
                when (age >=30 and age<40 ) then 'o30'
                when (age >=40 and age<50 ) then 'o40'
                else 'min50'
                    end
order by    state,
            age_group

(按案例陈述分组,而不是年龄)

另外,您可以在ORDER BY中使用列别名,但不能使用GROUP BY子句。您必须将完整的case语句复制并粘贴到GROUP BY中。