'Duplicated calculation using subquery
I am trying to reproduce the following calc:
((final_value - init_value) / init_value) * 100
Although I am getting the correct value I would like to ask if there is a better way to do this? At least, to avoid the same subquery twice (init_value)
SELECT (
(SELECT SUM(x)
FROM event
WHERE "year" = 2020)
-
(SELECT SUM(x)
FROM event
WHERE "year" = 2000))
/
(SELECT SUM(x)
FROM event
WHERE "year" = 2000)::FLOAT
* 100
Solution 1:[1]
There may be a an optimal Postgresql-specific method but generally you could use a conditional case expression, something like:
select (Sum(case when "year" = 2020 then x end) - Sum(case when "year" = 2000 then x end))
/ Sum(case when "year" = 2000 then x end)::float * 100
from event
where "year" in (2000,2020);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Stu |
