2

我想从包含字段(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

它运作良好。有人能帮我吗

4

1 回答 1

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 |
+-----------+-----------+    
于 2013-11-08T09:47:07.203 回答