SQL - 限制除TOP 6

时间:2016-03-16 13:29:34

标签: 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

此查询会产生前六个分类及其百分比的事件数。

现在我想生成第二个查询,它显示所有类别及其总数+百分比,!除了!我在第一个查询中检索到的6个类别。

所以,如果我说20个分类,我现在想要显示7-20号,一个名称为“其他”,并且所有类别的总数(7-20)+他们的百分比。

结果应如下所示:

Category|      Number of Inicdents |    Percentage
Other              200                      20%

其他应包含所有类别,但第一个查询除外..

这可能吗?

感谢任何帮助。

------------ EDIT -------------

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, 1295852105

干杯

1 个答案:

答案 0 :(得分:1)

由于您不知道最后一条记录,因此请使用大量数字,如下面的代码

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, 18446744073709551615;