在PostgreSQL查询中使用别名会返回“列不存在”

时间:2019-05-31 01:47:37

标签: sql postgresql alias calculated-columns

我正在尝试使用其他选择查询的别名来获取PostgreSQL中计算列的结果。我想将totalScore除以totalEmployee以获得该部分的平均值。但是,当我尝试执行计算时,会出现错误。

SELECT
    cast( sum( empskills.score ) as dec( 2 , 1 ) ) AS totalScore,
    skills.skill_name,  
    (SELECT
        count(employees.first_name)
        FROM
        sections
        INNER JOIN employees
        ON sections.id = employees.section_id
        WHERE
        sections.id = 2) as totalEmployees,
    (SELECT totalScore / totalEmployees) as finalResult
FROM
    employees
    INNER JOIN empskills
     ON employees.id = empskills.empid
    INNER JOIN skills
     ON empskills.skillid = skills.id
    INNER JOIN sections
     ON employees.section_id = sections.id
WHERE
    sections.id = 2
GROUP BY
    skills.skill_name
ERROR:  column "totalscore" does not exist
LINE 17:  (SELECT totalScore / totalEmployees)

我希望得到除法方程的结果。

1 个答案:

答案 0 :(得分:1)

根据您上面的SQL,我想您只是想获得每位员工每项技能的平均分数,我试图根据您上面的SQL编写如下的更简洁的SQL:

select
    s.skill_name,
    sum(k.score) as totalScore,
    count(distinct e.id) as totalEmployees,
    sum(k.score*1.0)/count(distinct e.id) as finalResult
from
    employees e
join
    empskills k on e.id = k.empid
join
    skills s on k.skillid = s.id
where
    e.section_id = 2
group by
    s.skill_name