如何在选择中划分不同表中的两个值

时间:2015-11-19 15:38:29

标签: sql oracle oracle12c

我需要划分两个表格nr1nr2,如下所示

SELECT COUNT(candidate.id) as nr1
FROM candidate
WHERE candidate.id=2



select count (candidate.id) as nr2
from candidate 
where candidate.id=2 or candidate.id = 3;

select nr1/nr2 from nr1, nr2;

问题是它们不在select查询之外。

3 个答案:

答案 0 :(得分:4)

您可以在单个查询中执行此操作。 AggregateSELECT数据有条件地

SELECT COUNT(CASE WHEN id = 2  THEN 1 END) 
       / COUNT(CASE WHEN id = 2 || id = 3 THEN 1 END) 
FROM candidate 

答案 1 :(得分:2)

在oracle中你可以创建一个cte。

With table1 as ( 
      SELECT COUNT(candidate.id) as nr1
      FROM candidate
      WHERE candidate.id=2
), 
table2 as (
     select count (candidate.id) as nr2
     from candidate 
     where candidate.id=2 or candidate.id = 3
)
SELECT table1.nr1 / table2.nr2
FROM table1
CROSS JOIN table2

但是一个简单的方法应该是使用条件SUM,你也必须验证div 0的情况。

WITH cte AS (
  SELECT         
       SUM(CASE WHEN candidate.id = 2 THEN 1 ELSE 0 END) as nr1,          
       SUM(CASE WHEN candidate.id IN (2,3) THEN 1 ELSE 0 END) as nr2
  FROM candidate
)
SELECT (CASE WHEN nr2 > 0 THEN nr1 / nr2 END) as result
FROM cte

答案 2 :(得分:1)

我会使用条件聚合来解决这个问题:

select (sum(case when c.id = 2 then 1.0 else 0 end) /
        sum(case when c.id in (2, 3) then 1.0 else 0 end)
       ) 
from candidate;