简体   繁体   中英

how to add new column and assign pre calculated values to it in sql query?

I have a table called

employee
---------
EmployeeNo(PK)
Fname
Lname
Status
Salary
Position
DeptNo(FK)

And I want to display the average salary in each department with the new column name Net_total ..confused.

Please try this :

ALTER TABLE employee
ADD Net_total INT NOT NULL;

UPDATE employee e
SET e.Net_total = (
SELECT AVG(e1.salary)
FROM employee e1
GROUP BY DeptNo
)

WHERE e1.DeptNo = e.DeptNo;

There is no need to create an extra field for this, you can calculate and show that value like this:

select e.EmployeeNo,
       e.Fname,
       e.Lname,
       e.Status,
       e.Salary,
       e.Position,
       e.DeptNo,
       (select avg(e2.Salary) from employee e2 where e2.DeptNo = e.DeptNo) as net_total
from   employee e

You can also create a view for this :

create view vwEmployee as
select e.EmployeeNo,
       e.Fname,
       e.Lname,
       e.Status,
       e.Salary,
       e.Position,
       e.DeptNo,
       (select avg(e2.Salary) from employee e2 where e2.DeptNo = e.DeptNo) as net_total
from   employee e

and now you can do

select * from vwEmployee

您可以对avg使用partition by

Select *, Avg(Salary) over(partition by deptno) as Net_Total from employee 

These are some of your options:

  1. Use DML triggers

from msdn documentation

A trigger is a special kind of stored procedure that automatically executes when an event occurs in the database server. DML triggers execute when a user tries to modify data through a data manipulation language (DML) event. DML events are INSERT, UPDATE, or DELETE statements on a table or view. These triggers fire when any valid event is fired, regardless of whether or not any table rows are affected.

So the ways is to ALTER your table to add a NULL-able column and add trigger which will update this column every time there is an INSERT or UPDATE operation

  1. Use Views

Create a view on top of this table where you add another column whose value is calculated dynamically based on your formula. You will always use the view instead of table where ever you need to reference the Net_total column

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM