Saa*_*hir 6 mysql sql select left-join
我的数据库如下所示
表名:订单明细
id oid pid pquantity pprice
--------------------------------------
1 1 5 2 10
2 1 6 3 5
3 1 7 1 20
5 2 8 1 5
6 2 9 1 5
7 3 5 5 10
Run Code Online (Sandbox Code Playgroud)
表名:订单
id odiscount oshipping
----------------------------
1 5 5
2 0 5
3 0 5
Run Code Online (Sandbox Code Playgroud)
我想获得每个订单的发票金额.(pquantity*pprice)-odiscount+oshipping.棘手的部分是每个订单可以在订单详细信息中有多个条目.所以我无法弄清楚如何照顾它.最终结果应该是
oid total
1 55
2 15
3 55
Run Code Online (Sandbox Code Playgroud)
我尝试使用以下SQL,但我无法弄清楚如何将订单详细信息中的多行考虑在内.
SELECT SUM((orderdetails.pprice*orderdetails.pquantity) - orders.odiscount + orders.oshipping) FROM orders LEFT JOIN orderdetails ON orderdetails.oid = orders.id GROUP BY orders.id
Run Code Online (Sandbox Code Playgroud)
我相信您甚至可以在不使用子查询的情况下做到这一点:
SELECT SUM(od.pquantity*od.pprice) + AVG(o.oshipping - o.odiscount)
FROM Orders o
INNER JOIN OrderDetails od
ON o.id = od.oid
GROUP BY o.id
Run Code Online (Sandbox Code Playgroud)
演示在这里:
| 归档时间: |
|
| 查看次数: |
103 次 |
| 最近记录: |