数据库 之 round函数

本文详细介绍了SQL中的ROUND()函数,包括其基本用法和两种形式,用于数值字段的四舍五入。通过两个实际的SQLZoo题目,展示了如何使用ROUND函数将人口数量和GDP转换为特定单位并保留指定小数位数。第一题涉及南美洲国家的人口和GDP数据,第二题要求展示人均GDP并四舍五入到最近的1000。通过实例,加深了对ROUND函数的理解和应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

用法

ROUND() 函数用于把数值字段舍入为指定的小数位数,主要有两种形式:

  1. ROUND(x,d) ,x 指要处理的数,d 是指保留几位小数,其中 d 可以为负数,当 d 为 -3 时表示保留整数到千位
  2. ROUND(x) ,其实就是ROUND(x,0),也就是默认d为0

例题

以SQLZoo上的两道题为例子:

1. 题目一

 Show the name and population in millions and the GDP in billions for the countries of the continent ‘South America’. Use the ROUND function to show the values to two decimal places.
 For South America show population in millions and GDP in billions both to 2 decimal places.
 该题目很简单,就是将人口数单位转变为百万级,将GDP转变为十亿级别,并且保留两位小数。答案如下:

select name,round(population/1000000,2),round(gdp/1000000000,2) 
from world 
where continent = 'South America'

2. 题目二

 Show the name and per-capita GDP for those countries with a GDP of at least one trillion (1000000000000; that is 12 zeros). Round this value to the nearest 1000.
 Show per-capita GDP for the trillion dollar countries to the nearest $1000.
 该题是求人均GDP,并且将数字保留到千位,让d = -3,答案如下:

select name,round(gdp/population,-3) 
from world 
where gdp > 1000000000000
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值