如何在select中计算两次值?

时间:2017-04-02 18:10:12

标签: postgresql

psql(9.6.1,server 9.5.5)

员工

     Column     |            Type             |                            Modifiers                            | Storage  | Stats target | Description 
----------------+-----------------------------+-----------------------------------------------------------------+----------+--------------+----    ---------
 employee_id    | integer                     | not null default nextval('employees_employee_id_seq'::regclass) | plain    |              | 
 first_name     | character varying(20)       |                                                                 | extended |              | 
 last_name      | character varying(25)       | not null                                                        | extended |              | 
 email          | character varying(25)       | not null                                                        | extended |              | 
 phone_number   | character varying(20)       |                                                                 | extended |              | 
 hire_date      | timestamp without time zone | not null                                                        | plain    |              | 
 job_id         | character varying(10)       | not null                                                        | extended |              | 
 salary         | numeric(8,2)                |                                                                 | main     |              | 
 commission_pct | numeric(2,2)                |                                                                 | main     |              | 
 manager_id     | integer                     |                                                                 | plain    |              | 
 department_id  | integer 

我需要提取员工编号,姓氏,工资,工资增加15.5%(表示为整数),以及新旧工资之间的差异。

我这样做了:

select employee_id,
    last_name,
    salary,
    round(salary * 1.155, 0) as "New Salary",
    round(salary * 1.155, 0) - salary as "Increase"
from employees;

让我感到困扰的是,我已经两次计算了新工资。

我尝试在同一个选择中使用别名。像这样试验:

select 2 as val_a, val_a - 4; --not working

好吧,我的解决方案输出了可接受的结果。但是没有更好的解决方案吗?

2 个答案:

答案 0 :(得分:1)

如果你担心表现,这个计算真的没什么。一些优化器甚至可能在内部重用计算。

如果你必须自己动手,你可以使用这样的子查询:

select t.*,
    New_Salary - salary as Increase
from (
    select employee_id,
        last_name,
        salary,
        round(salary * 1.155, 0) as New_Salary,
    from employees
    ) t;

答案 1 :(得分:0)

你可以用子查询来编写它,如果你“挑剔”不计算两次相同的值:

SELECT
     *, "New Salary" - salary as "Increase"
FROM
(
    SELECT
        employee_id,
        last_name,
        salary,
        round(salary * 1.155, 0) as "New Salary"
    FROM 
        employees
) AS s0 ;

在实践中,运行几次时的差异是可以忽略的:

dbfiddle here