Oracle 11g多表关联查询需求:订单、订单项与产品表数据计算
Oracle 11g 订单统计查询实现
表结构与数据
order表
| id | status | date |
|---|---|---|
| 1 | 1 | 25-12-2022 |
orderitem表
| id | pid | qty | Uom(unit of measure) |
|---|---|---|---|
| 1 | 100 | 5 | KG |
| 1 | 101 | 10 | KG |
| 1 | 102 | 15 | KG |
productstable表
| pid | price | Uom(unit of measure) |
|---|---|---|
| 100 | 1 | KG |
| 101 | 2 | KG |
| 102 | 3 | KG |
期望输出
| date | quantity | Price |
|---|---|---|
| 25-12-2022 | 30 | 70 |
实现SQL语句
SELECT o.date, SUM(oi.qty) AS quantity, SUM(oi.qty * p.price) AS Price FROM "order" o JOIN orderitem oi ON o.id = oi.id JOIN productstable p ON oi.pid = p.pid GROUP BY o.date;
语句说明
- 通过
JOIN关联三张表:order表与orderitem表通过订单ID关联,orderitem表与productstable表通过商品ID关联; SUM(oi.qty)统计该订单下所有商品的总数量;SUM(oi.qty * p.price)计算每个商品的金额(数量×单价)后求和,得到订单总金额;- 按订单日期
o.date分组,确保每个订单日期对应一行统计结果。
内容的提问来源于stack exchange,提问作者Pearl
相关产品推荐
相关产品推荐

