0

我正在使用 Oracle 数据库。

我有一张桌子:汽车。

它包含三个字段

比赛 - 赛车 - 完成

Car 本质上是 ID 字段。种族是种族的名称。终点是汽车放置的位置:(1st, 2nd, 4th, DNF)。

我想返回某辆车在每个位置完成的次数,包括零个实例。所以最终的结果是:

Toyota
Finish         Amount
1st            3
2nd            0
3rd            2
DNF            0

当汽车没有第二名时,我尝试 NVL 返回零:从 Car = 'Toyota'; 的汽车中选择 Finish, count(nvl(finish)); 但这仍然只返回第一名和第三名的完成计数。

我几乎是 SQL 的初学者,所以我一直在阅读我可以在这个网站和其他地方找到的所有零计数问题,并且无法将建议概括为我的特定情况。

编辑以包括表格:我将表格包括在内以进行澄清。“种族”字段对于这项任务真的不重要,因为我只是想计算“完成”的位置。

CAR       RACE      FINISH
Toyota    DCA       1st
Toyota    NYC       3rd
Toyota    ATL       3rd
Toyota    PHI       1st
4

2 回答 2

0
select
  f.Finish,
  count(c.Finish) as Finish_Amount
from 
  (select '1st' as Finish from dual
   union all
   select '2nd' from dual
   union all
   select '3rd' from dual
   union all
   select 'DNF' from dual
  ) f
  left join Cars c 
    on f.Finish = c.finish
    and c.Car = 'Toyota'
    --and c.Race = 'Atlanta'
group by f.Finish
order by 1
于 2013-03-10T16:17:48.447 回答
0

这适用于所有汽车

select a.f,nvl(cnt,0) cnt
(select '1st' as f from dual
union
select '2nd' as f from dual
union
select '3rd' as f from dual
union
select 'DNF' as f from dual) a,
(select Finish,count(finish) as cnt from cars group by finish) b
where a.f=b.finish(+)

如果您只想要特定的汽车,只需包含一个给出汽车名称的位置条件,例如

(select Finish,count(finish) as cnt from cars where car='MARUTI' group by finish)
于 2013-03-10T17:05:30.727 回答