MySQL Order By和Group By问题

时间:2014-07-25 14:47:58

标签: mysql group-by

我在MySQL表中有两个字段:

q31
q31_theme

q31包含评论和q31_theme主题,因此数据如下所示:

q31               q31_theme
Sunny and hot     Good weather
Cold and wet      Bad weather
Sunshine          Good weather
Bright and sunny  Good weather
No comment        N/A
Foggy             Bad weather
Raining           Bad weather
Cloudy and cold   Bad weather

我想要做的是使用显示以下数据的查询来恢复数据:q31中的注释按字母顺序排列,但是按q31_theme排序,其中主题计数按降序排列,因此它看起来像像这样:

q31               q31_theme         Count
Cloudy and cold   Bad weather       4
Cold and wet      Bad weather       4
Foggy             Bad weather       4
Raining           Bad weather       4
Bright and sunny  Good weather      3
Sunny and hot     Good weather      3
Sunshine          Good weather      3
No comment        N/A               1

count列是主题中的评论数。

我尝试了以下内容,它带回来了

SELECT q31, q31_theme, COUNT( q31_theme ) AS Count
FROM  `results` 
GROUP BY q31_theme
ORDER BY Count DESC

这只会给每个主题带来一条评论,显然是一个分组问题(我认为),但我不知道如何达到我想要的结果(假设有可能)。

欢迎任何和所有建议。

1 个答案:

答案 0 :(得分:1)

select r.*, t.count
from results r
join
(
  SELECT q31_theme, COUNT(*) AS Count
  FROM results 
  where q31_theme is not null and q31_theme <> ''
  GROUP BY q31_theme
) t on t.q31_theme = r.q31_theme
ORDER BY t.Count DESC,
         r.q31 ASC