0

我将如何使用我定义为“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;
4

2 回答 2

1

您需要在应用除法之前使用 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
;
于 2020-04-16T14:19:27.427 回答
1

c.population在子句中添加列GROUP BY并重用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;
于 2020-04-16T14:22:02.510 回答