gpt4 book ai didi

mysql - sql 中的平均函数在 View 中不起作用

转载 作者:行者123 更新时间:2023-11-29 02:26:59 25 4
gpt4 key购买 nike

我想从包含字段(emp_code、emp_name、salary、Dept_code)的表名 Employee 创建一个 View

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

效果很好。谁能帮帮我

最佳答案

我无法复制这个结果(除非所有薪水都相同)。考虑提供适当的 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 |
+-----------+-----------+

关于mysql - sql 中的平均函数在 View 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19855781/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com