此主题与我之前的Combine fields from different rows on condition相关。
我调整了从此线程获得的查询以满足其他一些要求。
SELECT
a.Date,
a.orderid AS AZNr,
a.Typ,
ROUND(a.Fees, 2) AS Fees,
ROUND(b.Shipping, 2) AS Shipping,
ROUND(c.Price, 2) AS Price,
d.DeliveryLand
FROM
(SELECT
posteddate AS Date,
transactiontype AS Typ,
orderid,
SUM(amount) AS Fees
FROM
report
WHERE
amounttype = 'ItemFees'
GROUP BY orderid) a
LEFT JOIN
(SELECT
orderid, SUM(amount) AS Shipping
FROM
report
WHERE
amountdescription = 'Shipping'
GROUP BY orderid) b ON a.orderid = b.orderid
LEFT JOIN
(SELECT
orderid, SUM(amount) AS Price
FROM
report
WHERE
amountdescription = 'Principal'
GROUP BY orderid) c ON b.orderid = c.orderid
LEFT JOIN
(SELECT
DeliveryLand, ExternalOrderId
FROM
orders) d ON c.orderid = d.ExternalOrderId
ORDER BY Date DESC
我必须在最后一个表上执行LEFT JOIN
才能获得DeliveryLand,但并非报告表中的每个项目都在orders-table中有一个条目。
在我做了一些计算之后,我发现这个查询没有返回所有条目。应该有25个条目" typ" ="退款",但我只得到20个。某些订单可能包含其他订单(由orderid标识)可能没有的条目。
我做了另一个询问,总结了退款的费用,运费和价格:
SELECT
SUM(ROUND(a.Fees, 2)) AS Fees,
SUM(ROUND(b.Shipping, 2)) AS Shipping,
SUM(ROUND(c.Price, 2)) AS Price
FROM
(SELECT
orderid, SUM(amount) AS Fees
FROM
report
WHERE
amounttype = 'ItemFees'
AND transactiontype = 'Refund'
GROUP BY orderid) a
LEFT JOIN
(SELECT
orderid, SUM(amount) AS Shipping
FROM
report
WHERE
amountdescription = 'Shipping'
AND transactiontype = 'Refund'
GROUP BY orderid) b ON a.orderid = b.orderid
LEFT JOIN
(SELECT
orderid, SUM(amount) AS Price
FROM
report
WHERE
amountdescription = 'Principal'
AND transactiontype = 'Refund'
GROUP BY orderid) c ON b.orderid = c.orderid
前两个结果,费用和运费,总结正确(我得到原始数据进行比较),但最后一个,价格,是不正确的,它太多了。我猜有些数据会被LEFT JOIN
截断,但是我无法弄清楚原因和位置,尤其是当我总结相同的列时,#34; transactiontype&#34 ; ="订单"。
我不知道为什么有些数据被截断或丢失。有人可以帮助我解决这两个问题中令人困惑的JOIN吗?如果您需要更多信息,请询问。
提前谢谢!
€dited query:
SELECT
posteddate AS Date,
transactiontype AS Typ,
report.orderid AS AZNr,
ROUND(SUM((amounttype = 'ItemFees') * amount),
2) AS Fees,
ROUND(SUM((amountdescription = 'Shipping') * amount),
2) AS Shipping,
ROUND(SUM((amountdescription = 'Principal') * amount),
2) AS Price,
orders.DeliveryLand,
articles.ItemVAT AS VAT
FROM
report
LEFT JOIN
orders ON report.orderid = orders.ExternalOrderID
LEFT JOIN
articles ON report.sku = articles.ItemID
GROUP BY report.orderid , transactiontype
答案 0 :(得分:0)
我从简化查询开始,可以在没有JOIN
的情况下编写。我还要问{1} ROUND
之前SUM
为何会花费更长时间并且不那么准确。
我做:
SELECT orderid,
ROUND(SUM((amountdescription='ItemFees')*amount), 2)) AS Fees,
ROUND(SUM((amountdescription='Shipping')*amount), 2)) AS Shipping,
ROUND(SUM((amountdescription='Principal')*amount), 2)) AS Price
FROM report
WHERE transactiontype='Refund'
GROUP BY orderid
作为解释(amountdescription='ItemFees')
如果为真则返回1,如果不是则返回0,因此仅对与指定的每个条件匹配的金额进行求和..如果您愿意,可以使用更长的CASE
:
SUM(CASE WHEN *condition* THEN amount ELSE 0 END)
您可能会丢失原始查询中的一些数据,因为它依赖于链接的所有子表..如果没有Fees
则订单Shipping
和{{1}不会被退回。
<强>更新强>
不要忘记,如果您在同一个orderid上有两个交易类型,它们都将被视为相同的订单,并且都将包含在相同的金额中......以分别使用交易类型:
Price