2011-10-26 46 views
0

我有一個表MySQL的分組的狀態字段

id, location, status 
1, london, 1 
2, london, 0 
3, boston, 1 
4, boston, 1 

我想我的查詢,生成這樣的事: -

location, status_1, status_0 
london, 1, 1 
boston, 2, 0 

到目前爲止我有: -

select count(id) as freq, location from my_table 
group by location order by freq desc; 

我完全失去了從這裏去的地方。

回答

1

那種變換在任何客戶端發出查詢不如做到,但如果你必須這樣做,在數據庫中,然後

select location, 
    sum(status = 1) AS status_1, 
    sum(status = 0) AS status_0 
from my_table 
group by location 

這是一個有點hackish,但「狀態= 1」當status爲1時將評估爲一個布爾值true,其中MySQL將禮貌地轉換爲整數'1',然後進行總結。狀態爲0且狀態= 0的計算結果爲true時也是如此。

+0

這是手短,使用隱式轉換爲馬克說,爲'SUM(CASE WHEN狀態= 1 THEN 1 ELSE 0 END)' – MatBailie

+0

完美,謝謝 –

1

所以你想要統計每個城市每個狀態的記錄?

在下面的查詢中,我按位置分組(如你所做的),然後爲每個狀態添加一筆總和。總和內是一種情況,如果記錄匹配所需的狀態,則返回1,否則返回0。這樣,您可以有效地統計每個位置每個州的記錄數量。

select 
    a.location, 
    sum(case when a.status = 1 then 1 else 0 end) as status_1, 
    sum(case when a.status = 0 then 1 else 0 end) as status_0 
from 
    YourTable a 
group by 
    a.location 
1
select location, 
sum(case when status = 1 then 1 else 0 end) as status_1, 
sum(case when status = 0 then 1 else 0 end) as status_0, 
from my_table 
group by location;