限制计数并将其余部分作为"其他"

时间:2014-09-30 06:52:35

标签: mysql sql

我正在计算用于在饼图中显示的内容。我想用实际的投资类型按数字显示最高6位数,其余为"其他" as investmentType。

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

我需要的是还有一行有投资类型"其他"和投资金额" 7"。

1 个答案:

答案 0 :(得分:1)

您可能想尝试以下内容:

    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)。