是否可以按特定值进行分组?

时间:2013-04-26 07:25:01

标签: oracle10g

我有一个带有以下值的oracle数据库表

+------+--------+
| id   | Name   |
+------+--------+
|    0 | One    |
|    1 | Two    |
|    2 | Three  |
|    3 | four   |
|    4 | One    |
|    5 | One    |
|    6 | Two    |
|    7 | five   |
+------+--------+

我想计算名称为“One”,“Two”,其余名称的行数。 结果集应该像

+------+--------+
| name | count  |
+------+--------+
|  One | 3      |
+------+--------+
|  Two | 2      |
+------+--------+
|  Rest| 3      |
+------+--------+

任何帮助?

1 个答案:

答案 0 :(得分:4)

select
  case name
    when 'One' then 'One'
    when 'Two' then 'Two'
    else 'Rest'
  end name,
  count(*)
from
  my_table
group by
  case name
    when 'One' then 'One'
    when 'Two' then 'Two'
    else 'Rest'
  end

避免重复:

select
  name,
  count(*)
from (
  select
    case name
      when 'One' then 'One'
      when 'Two' then 'Two'
      else 'Rest'
    end name
  from
    my_table)
group by
  name