我想从包含字段(emp_code,emp_name,salary,Dept_code)的表名Employee创建一个视图
create view dept_avg_salary as select dept_code , avg(salary) as average
from employee
group by dept_code
虽然上面的查询运行良好,但在平均列中,每行都存储相同的值9999.9999。但是,如果我运行查询
select dept_code , avg(salary) as average
from employee
group by dept_code
效果很好。 有人可以帮助我
答案 0 :(得分:2)
我无法复制此结果(除非所有工资都相同)。考虑提供适当的DDL,以便我们可以看到你的表是如何构建的......
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 |
+-----------+-----------+