0

我有一张表格,列出了我们收到的订单。每个订单一行。

第二个表记录与订单相关的交易。

我正在尝试生成一份报告,该报告显示每行和每行的一个订单,以显示各种交易类型的总价值。

我的查询是:

select 
orders.orderID, 
customers.username, 
(select sum(amount) from transactions where transactions.orderID=orders.orderID and transactionType IN (17) ) cost,
(select sum(amount) from transactions where transactions.orderID=orders.orderID and transactionType IN (18,19,20) ) surcharges,
(select sum(amount) from transactions where transactions.orderID=orders.orderID and transactionType IN (21,22) ) payments_received
from orders 
left join customers on orders.customerID=customers.customerID 
order by orderID

但这很慢。我在适当的列上有索引。

我是否可以避免执行三个子查询,而只运行一个查询出成本、附加费和 Payments_received 的查询?

4

1 回答 1

3

Something like this should do it:

SELECT orders.orderid
     , customers.username
     , Sum(CASE WHEN transactions.transactiontype IN (17        ) THEN transactions.amount END) As cost
     , Sum(CASE WHEN transactions.transactiontype IN (18, 19, 20) THEN transactions.amount END) As surcharges
     , Sum(CASE WHEN transactions.transactiontype IN (21, 22    ) THEN transactions.amount END) As payments_received
FROM   orders
 LEFT
  JOIN customers
    ON customers.customerid = orders.customerid
 LEFT
  JOIN transactions
    ON transactions.orderid = orders.orderid
GROUP
    BY orders.orderid
     , customers.username
ORDER
    BY orders.orderid
于 2013-09-13T15:22:38.430 回答