如何拥有一个'其他' MySQL查询中的行,用于对不太重要的结果进行分组

时间:2016-03-24 13:08:08

标签: mysql

进行以下查询。这使我获得了销售单位的前10个目的地,以及目的地在所有目的地销售的总单位份额。

有124个单独的结果,但是前10个以下的任何比例通常相当微不​​足道(小于1%)。

是否可以有一个查询,它将按单位给出前9个结果,然后是第10个'其他'行,将总结其余结果?

或者这是一个2查询工作吗?

SELECT a.destination,
       SUM(a.units) AS units,
       SUM(a.units) / b.total * 100 AS `share`
    FROM range_data AS a
    CROSS JOIN (SELECT SUM(units) AS total
                    FROM range_data) AS b
    GROUP BY a.destination
    ORDER BY units DESC
    LIMIT 10;

当前结果集

destination units   share
United Kingdom  433360  21.5943
Turkey  323657  16.1278
China   123264  6.1422
Russia  121595  6.0591
United States   106338  5.2988
Israel  97461   4.8565
Un Arab Emir    85221   4.2466
Egypt   51572   2.5698
Hong Kong   48932   2.4383
Suriname    44650   2.2249

所需的结果集

destination units   share
United Kingdom  433360  21.5943
Turkey  323657  16.1278
China   123264  6.1422
Russia  121595  6.0591
United States   106338  5.2988
Israel  97461   4.8565
Un Arab Emir    85221   4.2466
Egypt   51572   2.5698
Hong Kong   48932   2.4383
Other   165854  8.8766

1 个答案:

答案 0 :(得分:1)

这是一个2查询作业,但您可以使用union将2个查询合并为一个。第一个查询将与原始查询相同,只是它将有一个限制9,而不是10.另一个查询将总结所有其他查询:

(SELECT a.destination,
   SUM(a.units) AS units,
   SUM(a.units) / b.total * 100 AS `share`
FROM range_data AS a
CROSS JOIN (SELECT SUM(units) AS total
                FROM range_data) AS b
GROUP BY a.destination
ORDER BY units DESC
LIMIT 9)
UNION
(SELECT 'other',
   SUM(a.units) AS units,
   SUM(a.units) / b.total * 100 AS `share`
FROM range_data AS a
CROSS JOIN (SELECT SUM(units) AS total
                FROM range_data) AS b
LEFT JOIN (SELECT c.destination
           FROM range_data AS c
           GROUP BY c.destination
           ORDER BY SUM(c.units) DESC
           LIMIT 9) t ON a.destination=t.destination
WHERE t.destination IS NULL)
ORDER BY IF(destination='other',0,units) DESC

最后order by是为了确保其他'}显示在列表的底部。