MySQL SUM 不适用于相同的数值

MySQL SUM not working on same number values

我在数据库中有多个基于货币的订单。 当我尝试 select 订单统计时,MySQL SUM 没有计算相同的值。

例如,我在两个 2550 的订单上有相同的价格,但只计算一个订单的总和,如果我将一个订单的价格更改为 2551,它工作正常。

    $this->db->select('
    SUM(distinct(IF(EUR.amount>0 AND EUR.stat="1",(EUR.amount),"0"))) as EUR,
    SUM(distinct(IF(EUR.stat="3",(EUR.amount),"0"))) EURPriceAdd,
    SUM(distinct(IF(EUR.amount>0 AND EUR.stat="1",(EUR.amount),"0")-IF(EUR.stat="2",(EUR.amount),"0")+IF(EUR.stat="3",(EUR.amount),"0"))) as EURProfit,

    SUM(distinct(IF(USD.amount>0 AND USD.stat="1",(USD.amount),"0"))) as USD,
    SUM(distinct(IF(USD.stat="3",(USD.amount),"0"))) USDPriceAdd,
    SUM(distinct(IF(USD.amount>0 AND USD.stat="1",(USD.amount),"0")-IF(USD.stat="2",(USD.amount),"0")+IF(USD.stat="3",(USD.amount),"0"))) as USDProfit,,
    ', false);
    $this->db->join('orders_prices AS EUR', 'EUR.currency = 2 AND EUR.order_id = orders.id', 'LEFT');
    $this->db->join('orders_prices AS USD', 'USD.currency = 1 AND USD.order_id = orders.id', 'LEFT');
    $this->db->join('orders_address', 'orders_address.order_id = orders.id');
    $this->db->join('exchange_rate', 'MONTH(exchange_rate.date) = MONTH(orders.converted_at) AND YEAR(exchange_rate.date) = YEAR(orders.converted_at)', 'INNER');

    $this->db->group_by('orders_address.country');
    $directionIncomes = $this->db->get('orders')->result();

我找到了主要问题。 加入“exchange_rates”table导致的错误结果。 当我尝试加入汇率数据库时 returns 结果比他实际多得多。

这是SQL查询:


SELECT SUM(IF(USD.amount>0 AND USD.stat="1", (USD.amount), "0")) as USD, SUM(IF(USD.stat="3", (USD.amount), "0")) USDPriceAdd, SUM(IF(USD.amount>0 AND USD.stat="1", (USD.amount), "0")-IF(USD.stat="2", (USD.amount), "0")+IF(USD.stat="3", (USD.amount), "0")) as USDProfit
FROM `orders`
LEFT JOIN `orders_prices` AS `USD` ON `USD`.`currency` = 1 AND `USD`.`order_id` = `orders`.`id`
LEFT JOIN `orders_address` ON `orders_address`.`order_id` = `orders`.`id`
LEFT JOIN `exchange_rate` ON `exchange_rate`.`currency`="1"
WHERE `orders`.`pay_status` = 3
AND `orders`.`status` > 1
AND `orders`.`status` < 8
AND `orders_address`.`country` = 'BY'
AND DATE(orders.converted_at) >= '2021-01-01'
AND DATE(orders.converted_at) <= '2021-06-15'
GROUP BY `orders_address`.`country`

exchange_rates

的数据结构

https://imgur.com/WhRS5cL

https://i.imgur.com/VdsNL5W.png

您正在做的 SUM(distinct(IF(EUR.amount>0 ... 仅对不同的值求和(我想,我不知道有这样的选项)。使用 SUM(IF(EUR.amount>0 ... 代替

第三次连接错误。您将每个订单加入 exchange_rate 中的所有行(其中货币 = 1)。我想,您想要的是订单和 exchange_rate 表格中的相同货币和相同日期。