PostgreSQL中的整除截断
作者:互联网
开发同学说,在自己的测试环境中,相同的数据和相同的sql,在mysql和pg中查询出来的结果却不同。问是不是他装的数据库有问题了或者sum函数用错了。
以下是测试数据:
postgres=# select * from emp; empno | ename | job | mgr | hiredate | sal | comm | deptno -------+--------+-----------+------+------------+------+------+-------- 7369 | SMITH | CLERK | 7902 | 1980-12-17 | 800 | | 20 7499 | ALLEN | SALESMAN | 7698 | 1981-02-20 | 1600 | 300 | 30 7521 | WARD | SALESMAN | 7698 | 1981-02-22 | 1250 | 500 | 30 7566 | JONES | MANAGER | 7839 | 1981-04-02 | 2975 | | 20 7654 | MARTIN | SALESMAN | 7698 | 1981-09-28 | 1250 | 1400 | 30 7698 | BLAKE | MANAGER | 7839 | 1981-05-01 | 2850 | | 30 7782 | CLARK | MANAGER | 7839 | 1981-06-09 | 2450 | | 10 7788 | SCOTT | ANALYST | 7566 | 1982-12-09 | 3000 | | 20 7839 | KING | PRESIDENT | | 1981-11-17 | 5000 | | 10 7844 | TURNER | SALESMAN | 7698 | 1981-09-08 | 1500 | 0 | 30 7876 | ADAMS | CLERK | 7788 | 1983-01-12 | 1100 | | 20 7900 | JAMES | CLERK | 7698 | 1981-12-03 | 950 | | 30 7902 | FORD | ANALYST | 7566 | 1981-12-03 | 3000 | | 20 7934 | MILLER | CLERK | 7782 | 1982-01-23 | 1300 | | 10 (14 rows) postgres=# select (sum(case when deptno=10 then sal end)/sum(sal))*100 as pct from emp; pct ----- 0 (1 row) postgres=#
和
mysql> select * from emp; +-------+--------+-----------+------+------------+------+------+--------+ | EMPNO | ENAME | JOB | MGR | HIREDATE | SAL | COMM | DEPTNO | +-------+--------+-----------+------+------------+------+------+--------+ | 7369 | SMITH | CLERK | 7902 | 1980-12-17 | 800 | NULL | 20 | | 7499 | ALLEN | SALESMAN | 7698 | 1981-02-20 | 1600 | 300 | 30 | | 7521 | WARD | SALESMAN | 7698 | 1981-02-22 | 1250 | 500 | 30 | | 7566 | JONES | MANAGER | 7839 | 1981-04-02 | 2975 | NULL | 20 | | 7654 | MARTIN | SALESMAN | 7698 | 1981-09-28 | 1250 | 1400 | 30 | | 7698 | BLAKE | MANAGER | 7839 | 1981-05-01 | 2850 | NULL | 30 | | 7782 | CLARK | MANAGER | 7839 | 1981-06-09 | 2450 | NULL | 10 | | 7788 | SCOTT | ANALYST | 7566 | 1982-12-09 | 3000 | NULL | 20 | | 7839 | KING | PRESIDENT | NULL | 1981-11-17 | 5000 | NULL | 10 | | 7844 | TURNER | SALESMAN | 7698 | 1981-09-08 | 1500 | 0 | 30 | | 7876 | ADAMS | CLERK | 7788 | 1983-01-12 | 1100 | NULL | 20 | | 7900 | JAMES | CLERK | 7698 | 1981-12-03 | 950 | NULL | 30 | | 7902 | FORD | ANALYST | 7566 | 1981-12-03 | 3000 | NULL | 20 | | 7934 | MILLER | CLERK | 7782 | 1982-01-23 | 1300 | NULL | 10 | +-------+--------+-----------+------+------------+------+------+--------+ 14 rows in set (0.00 sec) mysql> select (sum(case when deptno=10 then sal end)/sum(sal))*100 as pct from emp; +---------+ | pct | +---------+ | 30.1464 | +---------+ 1 row in set (0.00 sec) mysql>
其实,这个和数值整除有关。
先看看mysql中对“/”的定义:
再看看pg中的定义:
此外,这里虽然不是sum()的问题,但是mysql和pg中,sum()的返回值也的确有所区别:
先看看mysql中对“sum”的定义:
再看看pg中的定义:
标签:12,20,1981,30,截断,PostgreSQL,整除,NULL,7698 来源: https://www.cnblogs.com/abclife/p/14266103.html