亚马逊为其市场客户提供CSV报告,其中包含有关您销售的每件商品的信息。每篇文章有四行,如下所示:
+----------------------+------------+-------------------+--------+
| orderid | amounttype | amountdescription | amount |
+----------------------+------------+-------------------+--------+
| 305-2406165-0572365 | ItemPrice | Principal | 2.98 |
| 305-2406165-0572365 | ItemPrice | Shipping | 3.89 |
| 305-2406165-0572365 | ItemFees | Commission | -0.45 |
| 305-2406165-0572365 | ItemFees | ShippingHB | -0.59 |
+----------------------+------------+-------------------+--------+
正如您所看到的,每篇文章都有四行,其中两行是实际售价,两行是我必须支付给亚马逊的费用。
我使用MySQL将此CSV文件导入SQL表。选择包括价格在内的一些数据如下:
SELECT DISTINCT
report.posteddate AS Date,
orders.OrderID,
orders.ExternalOrderID AS AZNr,
report.amount AS ArtPrice
FROM
report,
orders
WHERE
orders.ExternalOrderID = report.orderid
AND report.amountdescription = 'Principal'
AND report.transactiontype = 'Order'
ORDER by Date DESC
为了获得没有发货的商品价格,我选择只获取amountdescription为“Principal”的行。可以忽略transactiontype以解决我的问题。
我想做什么:
我想提取amounttype为“ItemFees”的两个字段,将它们一起添加并将结果显示为单个字段。选择此选项后,行应如下所示:
+------------+---------+---------------------+----------+-------+
| Date | OrderID | AZNr | ArtPrice | Fees |
+------------+---------+---------------------+----------+-------+
| 24.07.2014 | 267720 | 305-2406165-0572365 | 2.98 | -1.04 |
+------------+---------+---------------------+----------+-------+
我尝试为两个行运行一个子查询,并选择amounttype =“ItemFees”并合并结果,但最后我发现错误说我的子查询返回多行。这是查询:
SELECT DISTINCT
report.posteddate AS Date,
orders.OrderID,
orders.ExternalOrderID AS AZNr,
report.amount AS ArtPrice,
(SELECT
SUM(report.amount)
FROM
report,
orders
WHERE
orders.ExternalOrderID = report.orderid
AND report.amountdescription = 'Commission') +
(SELECT
SUM(report.amount)
FROM
report,
orders
WHERE
orders.ExternalOrderID = report.orderid
AND report.amountdescription = 'ShippingHB') AS Fees
FROM
report,
orders
WHERE
orders.ExternalOrderID = report.orderid
AND report.amountdescription = 'Principal'
AND report.transactiontype = 'Order'
ORDER by Date DESC
是否有人知道如何使用给定条件从两个不同的行中总结两个值(请参阅WHERE子句)?另外,我需要提取运费值,但我认为这是同一个问题。
提前谢谢。
答案 0 :(得分:0)
您可以使用两个查询计算itemprice和itemfees并加入它们
select a.orderid, a.price, b.fees
from (select orderid, sum(amount) price from report where amounttype='ItemPrice' group by orderid) a
join (select orderid, sum(amount) fees from report where amounttype='ItemFees' group by orderid) b
on a.orderid = b.orderid
这假设至少有一行有itemprice,一行有itemfees。否则你应该使用外连接。