算上TOP 5,将其他所有数量计为"其他"

时间:2016-12-21 22:07:05

标签: sql-server tsql sql-server-2014

我有一张个人电脑桌,想要了解顶级个人电脑制造商。由于数据将以饼图形式显示,目前约有45家不同的制造商,我希望得到前5名的数量,然后将其他所有内容合并到“其他”中。

以下查询将返回制造商对所有PC的计数:

SELECT 
    f_assetmanufacturer,
    COUNT(*) as 'PCs'
FROM tb_assets 
GROUP BY f_assetmanufacturer

上面查询的示例输出是:

f_assetmanufacturer    PCs
-----------------------------
Dell                   100
HP                     50
Lenovo                 25
Acer                   24
Toshiba                23
Microsoft              20
Equus                  20
Thinix                 20
Advantech              20

所需的输出如下:

f_assetmanufacturer    PCs                   f_assetmanufacturer    PCs
-----------------------------                -----------------------------
Dell                   100                   Dell                   100
HP                     50                    Other                  100
Lenovo                 25          or        HP                     50
Acer                   24                    Lenovo                 25    
Toshiba                23                    Acer                   24
Other                  100                   Toshiba                23

我如何只选择前5名制造商,并将所有剩余的制造商合并为“其他”制造商。类别是为了简化饼图中的输出?

2 个答案:

答案 0 :(得分:4)

您可以通过两个级别的聚合执行此操作:

SELECT (CASE WHEN seqnum <= 5 THEN f_assetmanufacturer ELSE 'Other' END) as assetmanufacturer,
       SUM(PCs) as PCs
FROM (SELECT f_assetmanufacturer, COUNT(*) as PCs,
             ROW_NUMBER() OVER (ORDER BY COUNT(*) DESC) as seqnum
      FROM tb_assets 
      GROUP BY f_assetmanufacturer
     ) a
GROUP BY (CASE WHEN seqnum <= 5 THEN f_assetmanufacturer ELSE 'Other' END)
ORDER BY PCs DESC;

注意:您可能希望使用rank()dense_rank(),具体取决于您在“第五”位置处理关系的方式。

答案 1 :(得分:1)

您可以使用CTE构建两个集合并将数据合并在一起,如下所示:

with top5
as (
SELECT top 5
    f_assetmanufacturer,
    COUNT(*) as 'PCs'
FROM tb_assets 
GROUP BY f_assetmanufacturer
order by 2 desc)
,other
as(
select 'Other',
    COUNT(*) as 'PCs'
FROM tb_assets a
where not exists (select 'ne' from top5 t where a.f_assetmanufacturer = t.f_assetmanufacturer)))

select * from top5
union all
select * from other