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.
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
You can use avg with partition by
Select *, Avg(Salary) over(partition by deptno) as Net_Total from employee
These are some of your options:
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
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