Oracle SQL部门

时间:2015-01-25 09:06:04

标签: sql oracle

我有

SELECT 
COUNT(*) AS a,
SUM(CASE WHEN r.hn IS NOT NULL THEN 1 ELSE 0 END) AS b,
SUM(CASE WHEN r.hn IS NULL THEN 1 ELSE 0 END) AS c,
( ____ / ____ ) AS d
FROM
x
LEFT JOIN (SELECT DISTINCT xn FROM yn) r ON x.xn = y.xn;

我需要第4行的空白是设置为'a'和'c'的值,但我不确定正确的语法是什么。

2 个答案:

答案 0 :(得分:2)

您不能在查询的同一级别(except in the order by clause)中引用列别名,因此您必须像在@ juergend的答案中重复原始表达式,或使用内联视图:

SELECT a, b, c, a/c AS d
FROM (
  SELECT 
  COUNT(*) AS a,
  SUM(CASE WHEN y.hn IS NOT NULL THEN 1 ELSE 0 END) AS b,
  SUM(CASE WHEN y.hn IS NULL THEN 1 ELSE 0 END) AS c
  FROM x
  LEFT JOIN (SELECT DISTINCT xn FROM yn) y ON y.xn = x.xn
);

对于复杂的表达式,这更简单,更容易维护 - 如果表达式发生变化,您只需在一个地方修改它,从而降低出错的风险。

如果您尝试将d的空值与总数的比率设为c/a,那么您只需将该部分反转为100*c/a;如果你想要百分比,那么count(),可能舍入或截断到一定的精度。

正如Clockwork-Muse所提到的,由于sum()忽略了空值,你可以使用它来代替两个SELECT a, b, c, a/c AS d FROM ( SELECT COUNT(*) AS a, COUNT(y.hn) AS b, COUNT(*) - COUNT(y.hn) AS c FROM x LEFT JOIN (SELECT DISTINCT xn FROM yn) y ON y.xn = x.xn ); 调用:

c

...或者您也可以在外部查询中计算(b - a)d,但这会使{{1}}计算更加混乱。

答案 1 :(得分:1)

正确的语法是再次重写语句。您无法在select子句中重复使用别名。

SELECT COUNT(*) AS t,
       count(r.hn) AS c,
       SUM(case when r.hn IS NULL then 1 end) AS u,
       count(r.hn) / SUM(case when r.hn IS NULL then 1 end) AS p
FROM h
LEFT JOIN (SELECT DISTINCT hn FROM r) r ON h.hn = r.hn;