CASE声明中的COUNT

时间:2016-08-15 13:58:37

标签: sql postgresql

我编辑了我的原始请求,因为我认为我和其他人一样困惑。我想在大陆内做一些事件。对不起困惑

Private Sub Worksheet_Change(ByVal Target As Range)
    If Not Application.Intersect(Target, Range("E4")) Is Nothing Then
        Dim projectName As Variant
        projectName = [E4]
        Sheets(projectName).Activate
    End If
End Sub

这就是我想看的内容

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"

非常感谢

2 个答案:

答案 0 :(得分: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将使用该列。

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

答案 1 :(得分: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"