2014-10-28 41 views
0

考慮:Mysql的使用情況計算時語句

SELECT(count(c.id), 
    case when(count(c.id) = 0) 
      then 'loser' 
     when(count(c.id) BETWEEN 1 AND 4) 
      then 'almostaloser' 
     when(count(c.id) >= 5) 
      then 'notaloser' 
    end as status, 
    ... 

當一切都說過和做過,查詢作爲一個整體產生一組結果類似於這樣的:

Count | status 
    --------|------------- 
    2 | almostaloser //total count is between 2 and 4 
    --------|------------- 
    0 | loser   // loser because total count = 0 
    --------|------------- 
    3 | almostaloser //again, total count between 2 and 4 
    --------|------------- 

我想要實現:

一種方法來重新從上表中的信息,但添加第三列,將給出每個狀態的總數,如

select count(c.id) 
    case when(count(c.id) = 0) 
     then loser as status AND count how many of the total count does this apply to 

結果將類似於:

Count | status  |total_of each status | 
    --------|-------------|---------------------| 
    2 | almostaloser| 2     | 
    --------|-------------|---------------------| 
    0 | loser  | 1     | 
    --------|-------------|---------------------| 
    3 | almostaloser| 2     | 
    --------|-------------|---------------------- 

有人告訴我,這可以使用派生表來實現,但我還沒有能夠得到他們兩個,只有一個或其他。

+0

請出示你的表結構和一些樣本行數據 – 2014-10-28 21:10:47

回答

1

這可以用這個查詢可以實現(你必須把你原來的查詢作爲子查詢有兩處):

SELECT t1.*, t2.total_of_each_status 
    FROM (
    -- put here your query -- 
) t1 
    INNER JOIN (
    SELECT status, count(*) AS total_of_each_status 
     FROM (
     -- put here your query -- 
    ) t2 
     GROUP BY status 
) t2 ON t2.status = t1.status 
+0

滾泥的緣故,這把我放在正確的方向。儘管我仍然不知道我剛剛做了什麼,但是把它全部整理出來。大聲笑感謝m8 – Kisaragi 2014-10-29 00:24:27