簡體   English   中英

CASE語句上的COUNT

[英]A COUNT on a CASE Statement

我正在編輯我的原始請求,因為我認為自己和其他人都感到困惑。 我想統計一下各大洲的事件。 對困惑感到抱歉

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

非常感謝

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將使用該列。

另外,您確實應該有一個查詢表,可以查詢整個大陸。 像這樣的代碼塊往往會成為維護的噩夢,因為隨着時間的推移,它們被復制到新查詢中。

將原始查詢包裝為派生表。 然后, 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"

我會這樣

正如@GordonLinoff指出的,您確實想要表,在這里,我使用values語句內聯了一個表。 然后,當您要實現該表時,幾乎不需要更改查詢。

同樣,可能是這樣,這樣的聯接將比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')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM