2016-08-15 78 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')