2011-04-11 70 views
0

如何在此查詢上加入平均值?如何通過查詢將連接添加到mysql範圍個案組中?

select t.range, count(*) as num 
from 
    (select case 
     when price < 50000 then '0 - 49K' 
     when price >= 50000 and price < 100000 then '50 - 99K' 
     when price >= 100000 and price < 200000 then '100 - 199K' 
     ... 
     as range, 
     price 
     from table) as t 
group by range 

我已經試過

select t.range, count(*) as num, avg(b.val) 
from 
    (select case 
     when price < 50000 then '0 - 49K' 
     when price >= 50000 and price < 100000 then '50 - 99K' 
     when price >= 100000 and price < 200000 then '100 - 199K' 
     ... 
     as range, 
     price 
     from table) as t 
    left join table2 b on b.id = t.id 
group by range 

和其他各種微弱的嘗試無果。

+1

也許我錯了(這裏遲到了),但我沒有看到t字段中的id字段... – Marco 2011-04-11 20:17:03

回答

0

很難說完全不知道更多關於什麼是「表2」以及它是如何涉及到「餐桌」,但我首先想到的是做你的子查詢,而不是在它之外裏面加入:

select t.range, count(*) as num, avg(t.val) 
from 
    (select case 
     when price < 50000 then '0 - 49K' 
     when price >= 50000 and price < 100000 then '50 - 99K' 
     when price >= 100000 and price < 200000 then '100 - 199K' 
     ... 
     as range, 
     t1.price, 
     b.val 
     from table t1 
     left join table2 b on b.id = t1.id 
) as t 
group by range