查询合并(一些)行

Query to merge (some) rows

我目前正在尝试创建一个查询,将一些行合并到一个类别并对相关值求和。

我将尝试用下面的例子来说明它:

Country | Sales Jan | Sales Feb | Sales Mar
--------+-----------+-----------+----------
Austria |    100    |    110    |    120
Spain   |    120    |    130    |    140
Italy   |     70    |     50    |     70
Japan   |     10    |     10    |     10
Brazil  |     20    |     20    |     20
Mexico  |      5    |      5    |      5

查询应显示每个欧洲国家/地区的数据并将所有其他行合并到类别 "Other" 并汇总相关值。

结果应如下所示:

Country | Sales Jan | Sales Feb | Sales Mar
--------+-----------+-----------+----------
Austria |    100    |    110    |    120
Spain   |    120    |    130    |    140
Italy   |     70    |     50    |     70
Other   |     35    |     35    |     35

更新:应详细显示的国家/地区在字符串列表中指定(在本例中,列表将包含 "Austria"、"Spain"、"Italy")。因此,未包含在此列表中的每个国家都应通过查询合并到类别 "Other"。

试试这个:

select case when country in('Austria','Spain','Italy')
            then Country else 'Other' end as Country,
       sum(Jan) as Jan,
       sum(Feb) as Feb,
       sum(Mar) as Mar

from t
group by case when country in('Austria','Spain','Italy')
              then Country else 'Other' end

Fiddle http://sqlfiddle.com/#!4/93719/2