MySQL 在 Select 上添加和多列

MySQL Adding & Multiple Columns On Select

我的数据库如下所示

Table 姓名:订单详情

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

Table 姓名:订单

id       odiscount oshipping
----------------------------
  1       5       5        
  2       0       5        
  3       0       5  

我想获取每个订单的发票金额。 (pquantity*pprice)-odiscount+oshipping。棘手的部分是每个订单在订单详细信息中可以有多个条目。所以我无法弄清楚如何处理它。最终结果应该是

oid   total
1     55
2     15
3     55

我使用以下 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

您可以先将 order_details 查询分组,然后才将其加入 orders table:

SELECT sum_details - odiscount + oshipping
FROM   orders o
JOIN   (SELECT   oid, SUM(pquantity * pprice) AS sum_details
        FROM     order_details
        GROUP BY oid) d ON o.id = d.oid

我相信你甚至可以不使用子查询来做到这一点:

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

此处演示:

SQLFiddle