首批通过分布式安全可靠测评,为关键业务系统打造
查询中使用算术操作符
更新时间:2026-06-22 14:10:55
查询中常见的算术操作符包括 +(加)、-(减)、*(乘)、/(除)、-(取反)、MOD(取模)。这些操作符可以作用在数值数据类型的列上。本文通过具体示例介绍如何在查询中使用算术操作符。
示例
查询出符合条件的客户购买的每个商品的数量和价格。数量乘以价格就是每类商品的支付总额,可以在 select_list 增加一列 t2.ol_quantity * t3.i_price,并重命名为 item_sum_price。
创建
cust表。obclient> CREATE TABLE cust ( c_id NUMBER, c_first VARCHAR2(20), c_last VARCHAR2(20), c_credit NUMBER(10, 2) ); Query OK, 0 rows affected创建
ordr表。obclient> CREATE TABLE ordr ( o_id NUMBER, o_ol_cnt NUMBER, o_entry_d DATE ); Query OK, 0 rows affected创建
item表。obclient> CREATE TABLE item ( i_id NUMBER, i_name VARCHAR2(20), i_price NUMBER(10, 2) ); Query OK, 0 rows affected插入
cust表数据。obclient> INSERT INTO cust VALUES(101,'Ann','Smith',16.10), (102,'Madeleine','Johnson',23.00), (103,'Michael','Brown',9.05); Query OK, 3 rows affected Records: 3 Duplicates: 0 Warnings: 0插入
ordr表数据。obclient> INSERT INTO ordr VALUES(102,400,date'2020-01-23'), (103,400,date'2020-01-23'),(104,300,date'2020-09-18'), (105,100,date'2020-07-01'); Query OK, 4 rows affected Records: 4 Duplicates: 0 Warnings: 0插入
item表数据。obclient> INSERT INTO item VALUES(102,'Apple','12.9'), (103,'Banana','10.2'),(105,'Pear','9.8'); Query OK, 3 rows affected Records: 3 Duplicates: 0 Warnings: 0查询出符合条件的客户购买的每个商品的数量和价格。
obclient> SELECT t1.c_first, t1.c_last, t1.c_credit, t2.o_ol_cnt * t3.i_price item_sum_price, t2.o_entry_d, t3.i_name, t3.i_price FROM cust t1 JOIN ordr t2 ON (t1.c_id=t2.o_id) JOIN item t3 ON (t2.o_id=t3.i_id) ORDER BY t1.c_id, t2.o_id; +-----------+---------+----------+----------------+-----------+--------+---------+ | C_FIRST | C_LAST | C_CREDIT | ITEM_SUM_PRICE | O_ENTRY_D | I_NAME | I_PRICE | +-----------+---------+----------+----------------+-----------+--------+---------+ | Madeleine | Johnson | 23 | 5160 | 23-JAN-20 | Apple | 12.9 | | Michael | Brown | 9.05 | 4080 | 23-JAN-20 | Banana | 10.2 | +-----------+---------+----------+----------------+-----------+--------+---------+ 2 rows in set