限制计数并将剩余部分设置为“其他”

问题描述:

我正在计算一个在饼图中显示的东西。我只想用实际的投资类型显示最高的6个计数,其余的显示为投资类型“其他”。限制计数并将剩余部分设置为“其他”

SELECT i.investment_type AS investmentType, 
     COUNT(*) AS investmentCount 
    FROM investment i, 
     vertical v 
WHERE v.vertical_name = i.investment_type 
    AND v.type = 'STR' 
    AND i.status_funding = 'o' 
GROUP 
    BY i.investment_type 
ORDER 
    BY investmentCount desc 

上面的查询给了我一个结果

enter image description here

通过添加limit 6到查询我得到

enter image description here

我需要的是一个更加一行investmentType“其他“和investmentCount”7“。

+0

你正在使用什么样的SQL? MSSQL,MySQL,PostgreSQL,SQLite ......?所有这些系统之间有一些变化。 (你也应该把它添加到你的问题的标签) – personne3000 2014-09-30 07:15:01

+0

MySQL.Sorry。也会添加该标签。 – puppuli 2014-09-30 07:17:42

+0

@പുപ്പുലി..你有没有尝试子查询? – 2014-09-30 07:20:25

,你可能觉得像有一个尝试:

SELECT i.investment_type as investmentType,COUNT(*) as investmentCount FROM investment i,vertical v 
    WHERE v.vertical_name =i.investment_type AND v.type='STR' AND i.status_funding ='o' 
    group by i.investment_type order by investmentCount desc 
    limit 6 
UNION 
    SELECT "others" as investmentType, SUM(othersInvestmentCount) as investmentCount FROM (
     SELECT COUNT(*) as othersInvestmentCount FROM investment i,vertical v 
     WHERE v.vertical_name =i.investment_type AND v.type='STR' AND i.status_funding ='o' 
     group by i.investment_type order by investmentCount desc 
     limit 6, 4294967296 
    ) 

我没有测试此查询,你可以,如果你发现语法问题,对其进行编辑。涉及三个实际的查询,但它不应该是疯狂的缓慢(如果不需要更快的速度,那么不需要更快地尝试)。

我假设你的数据库中有少于2^32条记录,这对于MySQL数据库来说似乎是一个非常合理的假设(但如果你觉得不安全,就用2^64代替它)。