小编典典

根据条件合并来自不同行的字段

sql

亚马逊向其市场客户提供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

为了仅获得商品价格而不进行运输,我选择了仅获取金额描述为“委托人”的行。为了解决我的问题,可以忽略transactiontype。

我想做的事:

我想提取数量类型为“ 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条款)?另外,我需要提取运输价值,但是我认为这是相同的问题。

先感谢您。


阅读 227

收藏
2021-04-15

共1个答案

小编典典

您可以通过两个查询来计算itemprice和itemfee并将它们加入

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。否则,您应该使用外部联接。

2021-04-15