我有一张看起来像这样的表:
ID | STATUS | TYPE
----------------------------------------
x123 | A | High School
x122 | I | High School
x124 | F | High School
x125 | A | College
x126 | I | College
x127 | F | College
x128 | F | College
任何人都可以帮我提出一个oracle 8i的查询,它会像这样显示这个表
Type | Count A | Count I | Count F
------------------------------------------------------------
High School | 1 | 1 | 1
College | 1 | 1 | 2
谢谢!
答案 0 :(得分:6)
这是一种方法:
select t.type as "Type"
, sum(case when t.status = 'A' then 1 else 0 end) as "Count A"
, sum(case when t.status = 'I' then 1 else 0 end) as "Count I"
, sum(case when t.status = 'F' then 1 else 0 end) as "Count F"
from my_table t
group by t.type
order by t.type desc
如果您要返回特定列,则此方法有效,并且可以“计算”符合更复杂条件集的行。
[编辑]
(添加了DESC关键字以获得如OP所示的排序结果集,Rob van Wijk获得+1好抓!)
(Andomar做了一个很好的观察,在结果集中有越来越多的列,使用这种方法,语句变得不合适。还有其他方法来获得相同的结果集,如果唯一的“测试”是一个单列上的等式比较。)
Oracle 8i确实支持CASE表达式,不是吗?如果我没记错的话,Oracle 8没有。我们可以通过DECODE函数去“老学校”做同样的事情:
select t.type as "Type"
, sum(decode(t.status,'A',1,0)) as "Count A"
, sum(decode(t.status,'I',1,0)) as "Count I"
, sum(decode(t.status,'F',1,0)) as "Count F"
from my_table t
group by t.type
order by t.type DESC
[/编辑]
有时,我们要检查多个类型条件,并在多个计数中包含一行。我们可以得到一个总数
select t.type as "Type"
, sum(case when t.status in ('A') then 1 else 0 end) as "Count A"
, sum(case when t.status in ('I') then 1 else 0 end) as "Count I"
, sum(case when t.status in ('F') then 1 else 0 end) as "Count F"
, sum(case when t.status in ('A','I') then 1 else 0 end) as "#AI"
, sum(decode(sign(t.foo-t.bar),1,1,0)) as "#foo>bar"
, sum(decode(sign(10.0-t.foo),1,1,0)) as "#foo<10"
from my_table t
group by t.type
order by t.type desc
(只是要指出,一行可能满足多列的指定条件,因此可以多次“计数”。有时,这正是我们想要的。)