当前位置:网站首页>SQL Server AVG函数取整问题
SQL Server AVG函数取整问题
2022-06-24 09:40:00 【Cpsu】
SQL Sever的均值函数在求整数类型的数据均值是结果还是整数,并且不会四舍五入。也就是向下取整。这里先创建一个成绩表,并适当添加数据。
CREATE TABLE sic(
学号 nchar(10) not null,
课程号 nchar(10) not null constraint pk_lh primary key(学号,课程号),
成绩 int not null);
INSERT INTO sic
values ('01','01',80),
('01','02',90),
('01','03',99),
('02','02',60),
('02','03',80),
('03','01',80),
('03','02',80),
('03','03',80);

SELECT AVG(成绩) AS 均分
FROM sic
GROUP BY sic.学号

很明显学号为01的学生均分不应该为整数。这里有两个办法可以解决。
第一个就是在创建表的时候就将数据设置为float类型。
ALTER TABLE sic
ALTER COLUMN 成绩 FLOAT NOT NULL;
SELECT sic.学号,AVG(成绩) AS 均分
FROM sic
GROUP BY sic.学号;
#也可以使用DECIMAL(18,2)格式保留两位小数

第二种方法就是利用SQL Server的CAST或者CONVERT函数。
SELECT sic.学号,
AVG(
CAST (成绩 AS FLOAT)
) AS 均分
FROM sic
GROUP BY sic.学号
SELECT CAST(AVG(CONVERT(FLOAT,成绩)) AS DECIMAL(18,2)) AS 均分
FROM sic
GROUP BY sic.学号
边栏推荐
- 416 binary tree (first, middle and last order traversal iteration method)
- Literature Research Report
- linux下oracle服务器打开允许远程连接
- Distributed | how to make "secret calls" with dble
- 记录一下MySql update会锁定哪些范围的数据
- Oracle database expdp only exports tables
- Producer / consumer model
- LeetCode: 377. Combined sum IV
- SSH Remote Password free login
- 为什么 JSX 语法这么香?
猜你喜欢

About thinkphp5, use the model save() to update the data prompt method not exist:think\db\query- & gt; Error reporting solution

Basic operations on binary tree

415 binary tree (144. preorder traversal of binary tree, 145. postorder traversal of binary tree, 94. inorder traversal of binary tree)

大中型企业如何构建自己的监控体系

canvas 绘制图片

微信小程序学习之 实现列表渲染和条件渲染.

队列Queue

Canvas draw picture

Internet of things? Come and see Arduino on the cloud

Jcim | AI based protein structure prediction in drug discovery: impacts and challenges
随机推荐
SQL statistics of users logged in for N consecutive days
5 minutes, excellent customer service chat handling skills
PHP file lock
大中型企业如何构建自己的监控体系
js代理模式
How to improve the efficiency of network infrastructure troubleshooting and bid farewell to data blackouts?
Operator details
Endgame P.O.O
Algorithm - the K row with the weakest combat power in the matrix (kotlin)
十大证券公司哪个佣金最低,最安全可靠?有知道的吗
Geogebra instance clock
Impdp leading schema message ora-31625 exception handling
canvas 绘制图片
impdp导schema报ORA-31625异常处理
美国电子烟巨头 Juul 遭遇灭顶之灾,所有产品强制下架
413 binary tree Foundation
100 GIS practical application cases (XIV) -arcgis attribute connection and using Excel
Cicflowmeter source code analysis and modification to meet requirements
port 22: Connection refused
Go language development environment setup +goland configuration under the latest Windows