2014-10-09 71 views
0

不提供有關表結構及數據的詳細信息不分組組:SQL - 由預期

可能是什麼原因,此組:

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 

有沒有重複的行?

回答

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 
+0

是的,我知道。太累了yesteday,謝謝你:) – royskatt 2014-10-10 10:16:11

1

它是因爲你按年齡分組。 你的意思是按age_group分組,州?

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 

(組由case語句,而不是年齡)

在一個側面說明,您可以使用列別名在ORDER BY,但不是GROUP BY子句。您必須將完整的case語句複製並粘貼到GROUP BY中。