2016-08-15 77 views
-1

我editng我原来的要求,因为我认为我已经困惑自己以及其他人。我想在大陆内做一些事件。很抱歉的混乱CASE声明COUNT

ID, --a unique incident number 

case 
when trim(both ' ' from cs.country) in ('France','UK',Germany) then 'Europe' 
when trim(both ' ' from cs.country) in ('Argentina','Peru','Brazil') 
then 'SouthAmerica'  
when trim(both ' ' from cs.country) in ('Bangladesh,'India','China') 
then 'Asia'  
end as "Continent" 

这是我希望看到

 Continent  Total   
     Europe   15 
     Asia   12 
     Asia    9 
     SouthAmerica  5 

非常感谢

+0

你说“COUNT在大陆上”。孟加拉国和印度都是亚洲国家,但数字不同,所以你的意思是按国家计数? – jarlh

+0

对不起,我省略了一个重要的部分,我有一个'事件'列,每次发生事故时都会给出一个唯一的ID。所以我在计算每个大陆的事故数 – whitz11

+0

那么孟加拉国和印度怎么有不同的数字呢?同一大陆... – jarlh

回答

1

包装你的原始查询了作为派生表什么。然后GROUP BY它的结果:

select Country, "Continent", count(*) 
from 
(
    select 
    cs.country, 
    case 
    when trim(both ' ' from cs.country) in ('France','UK',Germany) then 'Europe' 
    when trim(both ' ' from cs.country) in ('Argentina','Peru','Brazil') 
    then 'SouthAmerica'  
    when trim(both ' ' from cs.country) in ('Bangladesh,'India','China') 
    then 'Asia'  
    end as "Continent" 
    from tablename 
) 
group by Country, "Continent" 
3

的Postgres允许您使用表的别名在group by,所以你可以这样做:

select cs.country, 
     (case when trim(both ' ' from cs.country) in ('France', 'UK', Germany) 
      then 'Europe' 
      when trim(both ' ' from cs.country) in ('Argentina', 'Peru', 'Brazil') 
      then 'SouthAmerica'  
      when trim(both ' ' from cs.country) in ('Bangladesh', 'India', 'China') 
      then 'Asia'  
     end) as Continent, 
     count(*) 
from t 
group by country, continent; 

但是,你必须要小心,因为如果有一列在您的表格中调用continent,那么group by将会使用它。

此外,你真的应该有一个查阅大陆的参考表。像这样的代码块往往会成为维护的噩梦,因为随着时间的推移,它们会被复制到新的查询中。

+0

谢谢戈登这对我工作Postgres – whitz11

0

我会做这样的

由于@GordonLinoff指出你真的想要一个表,在这里我提出使用值语句行的表。然后,当您想要实现表格时,几乎不需要更改您的查询。

也可能是这种情况,像这样的连接将比CASE语句运行得更快......取决于很多事情 - 但我已经看到它发生了。

select cs.country, coalesce(tmp.con, 'unknown') as continent, count(*) 
from t cs 
left join (
    values 
    ('France', 'Europe'), 
    ('UK', 'Europe'), 
    ('Germany', 'Europe'), 
    ('Argentina', 'SouthAmerica'), 
    ('Peru', 'SouthAmerica'), 
    ('Brazil', 'SouthAmerica'), 
    ('Bangladesh', 'Asia'), 
    ('India', 'Asia'), 
    ('China', 'Asia') 
) as tmp(cou,con) ON cou = trim(both ' ' from cs.country) 
groupby cs.country, coalesce(tmp.con, 'unknown')