MySQL中的复杂SUM

时间:2014-07-06 15:50:44

标签: mysql

HY,

我有2个表,客户和供应商具有相同的列数

Client | Amount | Currency
Supplier | Amount | Currency

所有客户在某个时刻都可能成为供应商并逆转。我希望一个查询应该根据此规则计算到两个表中的不同合作伙伴的值:

Client Amount - Supplier Amount = Total Amount

,决赛桌应如下所示:

Partner | Currency | Amount Client | Amount Supplier | Total Amount

客户表:

Client | Amount | Currency
P1     | 100    | EUR
P2     | 50     | USD
P1     | 125    | EUR
P2     | 25     | EUR

供应商表

Supplier | Amount | Currency
P1       | 75     | EUR
P3       | 125    | USD
P2       | 50     | EUR
P1       | 75     | USD

预期输出应为:

Partner | Currency | Amount to receive | Amount to pay | Total amount
P1      | EUR      | 225               | 75            | 150
P1      | USD      | 0                 | 75            | -75
P2      | EUR      | 25                | 50            | -25
P2      | USD      | 50                | 0             | 50
P3      | USD      | 0                 | 125           | -125 

2 个答案:

答案 0 :(得分:2)

通过在两个表之间执行UNION ALL,您可以获得所有可能的合作伙伴代码的完整列表,以及它们各自的金额和货币。

但是,这还不足以区分他们的角色。在UNION查询中添加一个列,该列提供一个简单的静态字符串,用于标识角色是Client还是Supplier。然后,外部查询可以使用CASE聚合内的SUM()汇总那些,以确定要添加的角色。

<强> Here is a demonstration of this in action...

SELECT 
  Partner,
  Currency,
  -- Based on the static string value added in the UNION, determine
  -- whether Amount should be summarized, or just add 0
  -- This results in zeros instead of NULL for empty values, so it 
  -- has the added benefit of not requiring COALESCE()
  SUM(CASE WHEN type = 'Client' THEN Amount ELSE 0 END) AS `Amount to receive`,
  SUM(CASE WHEN type = 'Supplier' THEN Amount ELSE 0 END) AS `Amount to pay`,
  (SUM(CASE WHEN type = 'Client' THEN Amount ELSE 0 END)
  - SUM(CASE WHEN type = 'Supplier' THEN Amount ELSE 0 END)) AS `Total amount`
FROM (
  -- A UNION ALL combines all the Client/Supplier rows
  SELECT
    -- With a static string column added to identify the role
    -- (the source table)
    'Client' AS type,
    Client AS Partner,
    Amount,
    Currency
  FROM Client
  UNION ALL
  SELECT
    'Supplier' AS type,
    Supplier AS Partner,
    Amount,
    Currency
  FROM Supplier
) all_cs
GROUP BY 
  Partner,
  Currency

答案 1 :(得分:0)

试试这个SQL:

SELECT
     coalesce(client.Partner, supplier.Partner)  as Partner
    ,coalesce(client.Currency,supplier.Currency) as Currency
    ,coalesce(client.Amount,0)                   as "Amount Client"
    ,coalesce(supplier.Amount,0)                 as "Amount Supplier"
    ,coalesce(client.Amount,0)
    +coalesce(supplier.Amount,0)                 as "Total Amount"

FROM (
    SELECT
         Client      as Partner
        ,Currency
        ,sum(Amount) as Amount
    FROM CLients
    GROUP BY
          Client
        ,Currency
)clients
full outer join (
    SELECT
         Supplier    as Partner
        ,Currency
        ,sum(Amount) as Amount
    FROM CLients 
    GROUP BY
          Supplier 
        ,Currency
)supplier
   on supplier.Partner  = client.Partnr
  and supplier.Currency = client.Currency