欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

sql中mod()函数取余数的用法

程序员文章站 2022-03-28 17:49:18
mod(a,b) 在sql中的意思是 a / b 的余数(即 a % b )基础用法:如果id需要是偶数或者奇数时就可以使用mod。mod(id,2)=1 是指id是奇数。mod(id,2)=0 是指...

mod(a,b) 在sql中的意思是 a / b 的余数(即 a % b )

基础用法:如果id需要是偶数或者奇数时就可以使用mod。

mod(id,2)=1 是指id是奇数。

mod(id,2)=0 是指id是偶数。

select mod(3,2) from dual

执行如图:

sql中mod()函数取余数的用法

例如:根据身份证判定该员工是否是男女,从而实现对性别的更新。
身份证号的第17位数字,奇数为男性,偶数为女性
sex char(1) not null, --** 性别: 1 男,2 女

update table_name set 
sex = (case when mod(identifynumber[17],2) = '1' then '1' else  '2' end) 
where condition;

以上使用case wher语句,还可以用decode函数。(decode函数用法

例如:根据身份证号table2更新table1表员工的性别,生日,年龄。(下述使用的是informix数据库)

update table1  set 
sex = (select sex 
         from table2  
        where table2.t_id = table1.t_id 
          and table2.t_no = table1.t_no),
birthday = (select substr(identifynumber,7,8) 
              from table2         
             where table2.t_id = table1.t_id 
	           and table2.t_no = table1.t_no),
age = (select year(today) from dual) - ( select year( substr(identifynumber,7,8) ) 
                                           from table2 
                                          where table2.t_id = table1.t_id
                                            and table2.t_no = table1.t_no)
where t_id = '';

【实例】对 mod(63,8)、mod(120,10)、mod(15.5,3) 进行求余运算,输入的 sql 语句和执行结果如下所示。

mysql> select mod(63,8),mod(120,10),mod(15.5,3);
+-----------+-------------+-------------+
| mod(63,8) | mod(120,10) | mod(15.5,3) |
+-----------+-------------+-------------+
| 7 | 0 | 0.5 |
+-----------+-------------+-------------+
1 row in set (0.03 sec)

由运行结果可知,63 除以 8 余数是 7,120 除以 10 余数是 0,15.5 除以 3 余数是 0.5

到此这篇关于sql中mod()函数取余数的用法的文章就介绍到这了,更多相关sql mod()取余数内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!