在下一列定义中使用使用 'AS' 子句命名的列

Use column named using 'AS' clause in next column definition

我如何使用我定义为 'total_affected' 的列来代替长函数?..我觉得有更好的方法可以做到这一点,而不是重复上一行中的相同内容.我不确定如何定义它,以便我可以在下一栏中立即使用它。

SELECT c.name,
       COALESCE(sum(country_status_count.cured), 0) as cured,
       COALESCE(sum(country_status_count.dead), 0) as dead,
       cic.infected,
       SUM(COALESCE(cured, 0) + COALESCE(dead, 0) + infected) AS total_affected,
       (total_affected / c.population) as rate_of_infection <-- Something like this line instead of copying the whole function from the line above


FROM country_status_count

RIGHT JOIN country c ON country_status_count.country_id = c.id
RIGHT JOIN country_infection_counts cic ON c.name = cic.name

GROUP BY c.name, cic.infected, c.population
ORDER BY c.name ASC;

您需要在应用除法之前使用 CTE 设置数据集,或者在除法中复制 SUM() 子句。

WITH dataset AS
(
    SELECT c.name
         , COALESCE(sum(country_status_count.cured), 0) as cured
         , COALESCE(sum(country_status_count.dead), 0) as dead
         , cic.infected
         , SUM(COALESCE(cured, 0) + COALESCE(dead, 0) + infected) AS total_affected
         , c.population
      FROM country_status_count
     RIGHT JOIN country c ON country_status_count.country_id = c.id
     RIGHT JOIN country_infection_counts cic ON c.name = cic.name
     GROUP BY c.name, cic.infected
     ORDER BY c.name ASC;
)
SELECT *
     , (total_affected / population) as rate_of_infection <-- Something like this line
  FROM dataset
;

或者:

SELECT c.name
     , COALESCE(sum(country_status_count.cured), 0) as cured
     , COALESCE(sum(country_status_count.dead), 0) as dead
     , cic.infected
     , SUM(COALESCE(cured, 0) + COALESCE(dead, 0) + infected) AS total_affected
     , (SUM(COALESCE(cured, 0) + COALESCE(dead, 0) + infected)/ c.population) as rate_of_infection
  FROM country_status_count
 RIGHT JOIN country c ON country_status_count.country_id = c.id
 RIGHT JOIN country_infection_counts cic ON c.name = cic.name
 GROUP BY c.name, cic.infected, c.population
 ORDER BY c.name ASC
;

GROUP BY子句中添加列c.population并重复使用SUM(COALESCE(cured, 0) + COALESCE(dead, 0) + infected)进行计算,因为不能使用派生列total_affected:

SELECT c.name,
       COALESCE(sum(country_status_count.cured), 0) as cured,
       COALESCE(sum(country_status_count.dead), 0) as dead,
       cic.infected,
       SUM(COALESCE(cured, 0) + COALESCE(dead, 0) + infected) AS total_affected,
       (SUM(COALESCE(cured, 0) + COALESCE(dead, 0) + infected) / c.population) as rate_of_infection 
FROM country_status_count
RIGHT JOIN country c ON country_status_count.country_id = c.id
RIGHT JOIN country_infection_counts cic ON c.name = cic.name
GROUP BY c.name, c.population, cic.infected
ORDER BY c.name ASC;