从 SQL 查询中的计算列 select 创建新列

To make a new column from calculated column select in SQL Query

我有一个特定日期从 2020 年到 2022 年的特定日期的数据 covid 死亡记录。我想使用国家/地区的分组依据计算每个国家 2 年的死亡率。

我尝试按原样进行查询,但查询不起作用,因为不允许将子查询用作表达式。我如何使这个查询工作?谢谢。

SELECT 
   location, 
   sum(total_deaths) as total_deaths, 
   sum(total_cases) as total_cases, 
   (select SUM(total_deaths) 
    FROM CovidDeaths$ 
    GROUP BY location
   )/
   (select sum(total_cases) 
    FROM CovidDeaths$ 
    GROUP BY location
   ) *100 as DeathPercentage 
FROM CovidDeaths$ 
WHERE NOT (total_deaths is null 
           OR total_cases is null 
           OR continent is null
          ) 
GROUP BY location
ORDER BY 1 

*查询中的位置指的是国家

我尝试进行嵌套查询,但死亡百分比的值变为 0。

SELECT location, total_deaths1, total_cases1, total_deaths1/total_cases1*100 as Death_Percentage

FROM(

SELECT location, sum(total_deaths) as total_deaths1, sum(total_cases) as total_cases1

FROM CovidDeaths$ 

WHERE NOT (total_deaths is null OR total_cases is null OR continent is null) 

GROUP BY location

) as death

ORDER BY 1

你不需要在子查询中计算平均值,你可以在主查询中计算它

(SUM(total_deaths)/sum(total_cases))*100

更新

此计算列是您按位置分组的主查询的一部分:

SELECT 
location, 
sum(total_deaths) as total_deaths, 
sum(total_cases) as total_cases, 
(SUM(total_deaths)/sum(total_cases))*100
FROM CovidDeaths$ 
WHERE NOT (total_deaths is null 
       OR total_cases is null 
       OR continent is null
      ) 
GROUP BY location
ORDER BY 1 

许多数据库在除法中使用整数时使用整数运算。由于 01 之间没有整数,这意味着在乘以 100.

之前,您的所有值都被四舍五入为 0
  • 2 / 6 * 100 => 0 * 100 => 0

您可以简单地更改操作顺序

  • 100 * 2 / 6 => 200 / 6 => 66

或者,将值隐式转换为 non-integer 类型

  • 100.0 * 2 / 6 => 200.0 / 6 => 33.3333333

您还可以使用CAST()CONVERT()或其他函数显式转换data-type(可能是DECIMAL(18,6)FLOAT,取决于你的需要).

  • 具体语法取决于您使用的数据库
  • 但是你还没有指定是哪个数据库