如何从MySQL中的Alias列计算总和?

时间:2018-06-03 03:27:04

标签: mysql database mysql-workbench

我有两列:总数和百分比。我已经使用Alias创建了一个新的总列,现在我想通过查找此列和Alias总列的总和得到一个百分比列。我试过的内容如下:

SELECT sum(CASE when quality_class =1  then
    trees_ha else 0 end)/get_total_forest_plots()  +
sum(CASE when quality_class =2  then
    trees_ha else 0 end)/get_total_forest_plots()  as total ,

(sum(CASE when quality_class =1  then
     trees_ha else 0 end)/get_total_forest_plots()  +   
sum(CASE when quality_class =3  then
    trees_ha else 0 end)/get_total_forest_plots())/sum(total) *100 as percentage from (SELECT nested query from my_table);

我使用了这个sum(total)方法,但是我得到的错误是ERROR:列“total”不存在。

2 个答案:

答案 0 :(得分:1)

是的,您不能在同一级别使用别名。您需要编写一个上层查询来使用别名 考虑到代码的逻辑已经起作用,只需更正语法即可使用别名 这是怎么回事

SELECT 
   sum(CASE when quality_class =1 then trees_ha else 0 end)/get_total_forest_plots() + sum(CASE when quality_class =3 then trees_ha else 0 end)/get_total_forest_plots())/sum(initial_data.total) *1
FROM
    (SELECT 
    sum(CASE when quality_class =1 then trees_ha else 0 end)/get_total_forest_plots() + sum(CASE when quality_class =2 then trees_ha else 0 end)/get_total_forest_plots() as total 
From
<Table name> 
) initial_data

答案 1 :(得分:0)

选项1

SELECT 3 x, (SELECT 1+1) y, 3-(SELECT 1+1) z;

选项2

SELECT x, y, x-y z FROM
  ( SELECT 3 x, (SELECT 1+1) y) q