Tsql通过特定阈值下的结果聚合组作为"其他"

时间:2017-11-24 10:32:34

标签: sql sql-server

我有一个汇总查询,它给我这些结果:

289         Andria - BT
97          N/A
97          Barletta - BT
47          Cerignola - FG
34          Corato - BA
33          Trani - BT
21          Bari - BA
19          Bitonto - BA
18          Bisceglie - BT
18          San Ferdinando di Puglia - BT
15          Foggia - FG
14          Molfetta - BA
14          Terlizzi - BA
12          Altamura - BA
9           San Severo - RA
9           Trinitapoli - BT
8           Margherita di Savoia - BT
7           Lucera - FG
6           Giovinazzo - BA
5           Capurso - BA
5           Minervino Murge - BT
5           Spinazzola - BT
5           Venosa - PZ
4           Stornara - FG
4           Milano - PG
4           Palo del Colle - BA

我想将一些thresold(例如10)下的所有值加在一行中;

之类的东西
289         Andria - BT
97          N/A
97          Barletta - BT
47          Cerignola - FG
34          Corato - BA
33          Trani - BT
21          Bari - BA
19          Bitonto - BA
18          Bisceglie - BT
18          San Ferdinando di Puglia - BT
15          Foggia - FG
14          Molfetta - BA
14          Terlizzi - BA
12          Altamura - BA
<SUM>       OTHER   

查询基本上类似于:

select count(ID) as Count, ISNULL(Description, 'N/A') as City
from 
Table    
group by Description

我怎样才能达到这个效果? 谢谢

3 个答案:

答案 0 :(得分:2)

将计数移至cte。选择其中count> = 10的行和UNION ALL,其中行的总和为&lt; 10。

with cte as
(
    select count(ID) as Count, ISNULL(Description, 'N/A') as City
    from Table    
    group by Description
)
select * from cte where Count >= 10
UNION ALL
select SUM(count), 'Other' from cte where Count < 10

答案 1 :(得分:2)

试试这个:

SELECT SUM(CountID),City
FROM(
       select count(ID) as CountID, 
              CASE WHEN count(ID) < 10 
                   THEN 'Other' 
                   ELSE ISNULL(Description, 'N/A')
              END as City

      from Table    
      group by Description
)m
Group BY City

答案 2 :(得分:0)

对我来说有点不清楚,但是我会给你一些查询,这些查询略有不同。选择满意的你。

您需要的只是HAVING条款:

select count(ID) as Count, ISNULL(Description, 'N/A') as City
from 
Table    
group by Description
having count(ID) > 10

或者您可以使用此查询:

select count(ID), City from (
    select ID, ISNULL(Description, 'N/A') as City
    from Table    
    where ID > 10
) as A
group by City