SQL - 使用LIMIT进行SUM UP查询

时间:2016-03-16 16:16:41

标签: mysql sql

我的活动不知道如何解释我的问题所以请耐心等待我。

我目前的SQL查询是:

SELECT Count(CATEGORY),  COUNT(INCIDENT_ID), CATEGORY,

ROUND(Count(CATEGORY) * 100 / (SELECT Count(*) 
                              FROM   incident_view 
                              WHERE 
( create_month = Month(Now() - 
                INTERVAL 1 month) ) 
AND ( create_year = Year( 
      Now() - INTERVAL 1 month) ) 
AND customer_company_name = "Company"
   ), 1) AS Percentage
FROM   incident_view 
WHERE  ( create_month = Month(Now() - INTERVAL 1 month) ) 
 AND ( create_year = Year(Now() - INTERVAL 1 month) ) 
AND customer_company_name = "Company"
GROUP BY CATEGORY
ORDER BY COUNT(INCIDENT_ID) DESC
limit 6, 1525125215;

我的数据库有10个类别,此查询以7-10个最多记录检索类别。

如果我使用Query,我会从数据库中收到4个最低记录... 但我想将4个最低记录检索为一个名为“其他”的记录,其中包含(SUM)查询中的所有数据。

目前的示例(RESULT):

 Count(Category) | Category | Percentage
    10               Cat1       5.0
     15              Cat2       3.0
    20               Cat 3      4.0

但我希望结果看起来像:

Count(Category) | Category | Percentage
   45             Other       12.0

有没有达到这个结果?

感谢任何帮助。

干杯

1 个答案:

答案 0 :(得分:0)

你想要另一个subquery。 没有SQLFiddle,我无法对此进行测试,但它类似于:

Select Sum(category_count), 'other', sum(percentage) 
from (
SELECT Count(CATEGORY) as category_count,  COUNT(INCIDENT_ID), CATEGORY,

ROUND(Count(CATEGORY) * 100 / (SELECT Count(*) 
                              FROM   incident_view 
                              WHERE 
( create_month = Month(Now() - 
                INTERVAL 1 month) ) 
AND ( create_year = Year( 
      Now() - INTERVAL 1 month) ) 
AND customer_company_name = "Company"
   ), 1) AS Percentage
FROM   incident_view 
WHERE  ( create_month = Month(Now() - INTERVAL 1 month) ) 
 AND ( create_year = Year(Now() - INTERVAL 1 month) ) 
AND customer_company_name = "Company"
GROUP BY CATEGORY
ORDER BY COUNT(INCIDENT_ID) DESC
limit 6, 1525125215) as original_query;