如何使用 case 语句选择数据并分组?

Kin*_*rog 7 case

我试图通过使用 case 语句稍微操作数据,但似乎无法弄清楚。

Stops
--------------------
1Stop
1-Stop
1 stop
1 Stop
1stop
1 Stop
2-Stop
Run Code Online (Sandbox Code Playgroud)

我试图想出:

1-Stop.... 6
2-Stop.... 1
Run Code Online (Sandbox Code Playgroud)

我试过的是:

select CASE when 
Stops = '1Stop' OR 
Stops = '1 Stop' OR 
Stops = '1 stop' then '1-Stop' 
ELSE Stops END, count(*) 
from table group by Stops
Run Code Online (Sandbox Code Playgroud)

Tar*_*ryn 10

问题是你不能StopsGROUP BY. 在您使用时的查询中,GROUP BY它使用每一行的单独值。您需要使用子查询来获取结果:

select stops, count(*) Total
from  
(
  select 
    CASE 
      when Stops in ('1Stop', '1 Stop', '1 stop') then '1-Stop' 
      ELSE Stops
    END as Stops
  from yourtable
) d
group by stops;
Run Code Online (Sandbox Code Playgroud)

请参阅SQL Fiddle with Demo

或者,如果您不想使用子查询,那么您可以重复以下CASE表达式GROUP BY

select 
  CASE 
    when Stops in ('1Stop', '1 Stop', '1 stop') then '1-Stop' 
    ELSE Stops
  END as Stops,
  count(*)  as Total
from yourtable
group by 
  CASE 
    when Stops in ('1Stop', '1 Stop', '1 stop') then '1-Stop' 
    ELSE Stops
  END 
Run Code Online (Sandbox Code Playgroud)

参见SQL Fiddle with Demo