Question

I would like to create a view from a table name Employee containing fields (emp_code , emp_name , salary , Dept_code) as

create view dept_avg_salary as select dept_code , avg(salary) as average 
   from employee 
   group by dept_code

although the above query runs well, but in the average column the same value 9999.9999 is stored in every row . But if i run the query

select dept_code ,  avg(salary) as average 
    from employee 
    group by dept_code

it works well. Can someone help me

Was it helpful?

Solution

I can't replicate this result (except when all salaries are the same). Consider providing proper DDLs so we can see how your table is constructed...

CREATE TABLE employee(emp_code INT NOT NULL AUTO_INCREMENT PRIMARY KEY, emp_name VARCHAR(12) NOT NULL, salary INT NOT NULL, Dept_code CHAR(1) NOT NULL);

INSERT INTO employee VALUES
(1,'John',1000,'A'),
(2,'Paul',2000,'B'),
(3,'George',1000,'B'),
(4,'Ringo',3000,'A');

SELECT dept_code , AVG(salary) average FROM employee GROUP BY dept_code;
+-----------+-----------+
| dept_code | average   |
+-----------+-----------+
| A         | 2000.0000 |
| B         | 1500.0000 |
+-----------+-----------+

CREATE VIEW dept_avg_salary AS 
SELECT dept_code
     , AVG(salary) average 
  FROM employee 
 GROUP 
    BY dept_code;

SELECT * FROM dept_avg_salary;
+-----------+-----------+
| dept_code | average   |
+-----------+-----------+
| A         | 2000.0000 |
| B         | 1500.0000 |
+-----------+-----------+    
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top