Postgresql 如何不在select中计算两次值?
psql(9.6.1,服务器9.5.5) 员工Postgresql 如何不在select中计算两次值?,postgresql,Postgresql,psql(9.6.1,服务器9.5.5) 员工 Column | Type | Modifiers | Storage | Stats target | Description ----------------+-----------------------------+--------------------------
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
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;
使我烦恼的是,我已经计算了两次新的工资
我尝试在同一选择中使用alias。试验如下:
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
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;
嗯,我的解决方案输出了可接受的结果。但是,难道没有更好的解决方案吗?如果您担心性能,那么这种计算实际上什么都不是。一些优化器甚至可以在内部重用计算 如果必须自己执行,可以使用如下子查询:
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
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;
如果您“挑剔”不计算两次相同的值,则可以使用子查询编写:
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让我担心的主要是代码的可读性和风格。如果我的解决方案难看,或者你的建议风格更好?我觉得你的问题很好。尽管我建议使用标准别名,使用字母、数字和下划线,这样就不必使用双引号。到处都是双引号肯定会损害可读性。如果你担心性能,那就别担心。