当前位置:网站首页>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.学号
边栏推荐
猜你喜欢

Wechat applet learning to achieve list rendering and conditional rendering

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

Cookie encryption 4 RPC method determines cookie encryption

oracle池式连接请求超时问题排查步骤

How large and medium-sized enterprises build their own monitoring system

如何管理海量的网络基础设施?

Floating point notation (summarized from cs61c and CMU CSAPP)

Tutorial (5.0) 08 Fortinet security architecture integration and fortixdr * fortiedr * Fortinet network security expert NSE 5

Servlet fast foundation building

NVIDIA's CVPR 2022 oral is on fire! 2D images become realistic 3D objects in seconds! Here comes the virtual jazz band!
随机推荐
NVIDIA's CVPR 2022 oral is on fire! 2D images become realistic 3D objects in seconds! Here comes the virtual jazz band!
GeoGebra 实例 时钟
保健品一物一码防窜货营销软件开发
Geogebra instance clock
In depth study paper reading target detection (VII) Chinese English Bilingual Edition: yolov4 optimal speed and accuracy of object detection
Servlet fast foundation building
队列Queue
分布式 | 如何与 DBLE 进行“秘密通话”
MYSQL数据高级
indexedDB本地存储,首页优化
Desktop software development framework reward
买的长期理财产品,可以转短吗?
Symbol.iterator 迭代器
How to solve multi-channel customer communication problems in independent stations? This cross-border e-commerce plug-in must be known!
Go language development environment setup +goland configuration under the latest Windows
微信小程序學習之 實現列錶渲染和條件渲染.
十大证券公司哪个佣金最低,最安全可靠?有知道的吗
Oracle database expdp only exports tables
Literature Research Report
413 binary tree Foundation