将一个表中的SUM值与另一个表中的变量相乘

时间:2016-05-25 04:57:03

标签: mysql function sum multiplication

我有两张桌子:

  • t_shipment ,其中包含shipper_account,ship_value和ship_date(以及其他与此无关的

  • t_customer ,其中包含account_number和ship_fee(运费是指每次发货收取的费用,而且数量因帐户而异)(同样,该表还包含其他字段)< / p>

    • 注意:shipper_account完全引用account_number(虽然它不被视为外键)

我需要计算一天中来自t_shipment的帐户所做的所有交易的总和,然后将其乘以t_customer中相应的ship_fee。

然后我尝试了这个:

SELECT SUM(ship_value * (ship_fee)) as calculated_value
FROM t_shipment
INNER JOIN t_customer
ON shipper_account = account_number
WHERE ship_fee IS NOT NULL;

但它看起来并不正确。我想确保 SUM(cod_value * (cod_fee/100))部分确实返回每个托运人的ship_value乘以他们自己的ship_fee的总和。 (例如,而不是所有出货单的所有ship_value的SUM乘以所有ship_fee的SUM。

e.g。如果我有数据集:

__________________________________________
|shipper_account | ship_value | ship_date |
|1000000000      |    240     |(some date)|
|1000000000      |     60     |(some date)|
|2000000000      |    100     |(some date)|
-------------------------------------------
_____________________________
|account_number  | ship_fee |
|1000000000      |    0.5   |
|2000000000      |    0.1   |
-----------------------------

结果应该是:

  • 托运人帐户的总和1000000000(240 + 60)乘以0.5 = 150
  • 托运人帐户的总和2000000000(100)乘以0.1 = 10
  • 那些的总和(150 + 10 = 160)

而不是

  • 所有ship_values(360)的总和乘以ship_fee的SUM(0.6)= 216

那么,最简​​单的解决方案是什么?

2 个答案:

答案 0 :(得分:2)

希望这会起作用

SELECT SUM(s.ship_value *c.ship_fee) as calculated_value 
FROM t_customer as c inner join t_shipment as s 
on c.account_number = s.shipper_account 
where c.ship_fee is not null 
group by c.account_number

或者

SELECT SUM(ship_value * (ship_fee)) as calculated_value 
FROM t_shipment INNER JOIN t_customer 
ON shipper_account = account_number 
WHERE ship_fee IS NOT NULL GROUP BY account_number;

答案 1 :(得分:0)

您的查询对我来说是正确的,虽然它对日期缺少WHERE限制,您也可以使用COALESCE()代替WHERE IS NOT NULL

SELECT SUM(ship_value * COALESCE(ship_fee, 0.0)) AS calculated_value
FROM t_shipment
INNER JOIN t_customer
    ON shipper_account = account_number
WHERE ship_date = '2016-05-25'