简体   繁体   中英

Oracle SQL division

I have

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;

I need the blanks on line 4 to be the values set to 'a' and 'c', I'm not sure what the correct syntax is though.

You can't refer to column aliases in the same level of the query ( except in the order by clause ), so you have to either repeat the original expression as in @juergend's answer, or use an inline view:

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
);

For complicated expressions this is a bit simpler and easier to maintain - if the expression changes you only have to modify it in one place, reducing the risk of a mistake.

If you're trying to make d the ratio of nulls to the total then you just need the division reversed, as c/a ; and if you wanted the percentage then 100*c/a , possibly rounded or truncated to a certain precision.

And as Clockwork-Muse mentioned, since count() ignores nulls, you coudl use that instead of the two sum() calls:

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
);

... or you could calculate c in the outer query too, as (b - a) , though that makes the d calculation messier.

The correct syntax is to rewrite the statements again. You can't re-use alias names in the select clause.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM