2014-10-28 39 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