1

如何查看前 5 个结果并将其余结果分组到“其他”下?如果我有一个带有“页面”字段的表“访问”,它有 100 行,我需要结果如下:

Other    40
/        20
/about   15
/contact 10
/welcome 10
/test     5

我自己无法在一个查询中做到这一点。

4

2 回答 2

2

尝试

select case when v2.page is not null 
              then v1.page 
              else 'other' 
       end, 
       count(*)
from visits v1
left join 
(
  select page, count(*) as pcount
  from visits
  group by page
  order by pcount desc
  limit 5
) v2 on v1.page = v2.page
group by case when v2.page is not null 
              then v1.page 
              else 'other' 
         end
于 2013-09-05T14:25:04.290 回答
0

有一个 SQL Fiddle http://sqlfiddle.com/#!2/8b116/4

W3Schools 上的 SQL 左连接 http://www.w3schools.com/sql/sql_join_left.asp

SELECT CASE WHEN v2.page IS NOT NULL
  THEN v1.page
  ELSE 'other'
  END AS page,
  count(*) AS count
FROM visits v1
LEFT JOIN
(
  SELECT page, COUNT(*) AS pcount
  FROM visits
  GROUP BY page
  ORDER BY pcount DESC
  LIMIT 5
) v2 ON v1.page = v2.page
GROUP BY page
ORDER BY count DESC
于 2013-09-25T03:19:21.187 回答