我有两个 mysql 表。 第一张表:
cost_id| cost_customer_id | cost_total | cost_date
1 | 1 | 50 | 2019-01-03
2 | 2 | 120 | 2019-02-03
3 | 1 | 70 | 2019-03-21
4 | 2 | 35 | 2019-04-03
5 | 3 | 14 | 2019-05-07
6 | 1 | 84 | 2019-06-03
第二张表:
inv_id | inv_customer_id | inv_total | inv_date
1 | 1 | 150 | 2019-01-05
2 | 2 | 20 | 2019-02-06
3 | 1 | 90 | 2019-03-21
4 | 1 | 3 | 2019-04-03
5 | 3 | 94 | 2019-05-09
6 | 2 | 11 | 2019-06-08
7 | 1 | 99 | 2019-07-06
8 | 2 | 71 | 2019-08-04
9 | 1 | 45 | 2019-09-02
所以我想要返回的是:
customer_id | sum_inv_total | sum_cost_total | balance | avg_inv_date
1 | 387 | 204 | 183 | 2019-05-31
2 | 102 | 155 | -53 | null
3 | 94 | 14 | 80 | 2019-05-09
即,在扣除由 inv_date 订购的成本后获得每个客户的平均 inv_date,例如客户 #1;未结发票的平均 inv_date:
inv_id | inv_customer_id | inv_total | inv_date | status
1 | 1 | 150 | 2019-01-05 | closed (still below cost)
3 | 1 | 90 | 2019-03-21 | open (reached total cost: 204)
4 | 1 | 3 | 2019-04-03 | open
7 | 1 | 99 | 2019-07-06 | open
9 | 1 | 45 | 2019-09-02 | open
我可以尝试以下查询,但完成时间太长,而且只针对一位客户:
SELECT
sum_cost_total,
SUM(inv_total_str) AS sum_inv_total ,
FROM_UNIXTIME(AVG(UNIX_TIMESTAMP(inv_date_str))) AS avg_inv_date
FROM
(
SELECT
o1.inv_total AS inv_total_str, o1.inv_date AS inv_date_str,
(
SELECT SUM(cost_total)
FROM company_costs
WHERE cost_customer_id = o1.inv_company_customer_id
) AS sum_cost_total
FROM invoices o1
INNER JOIN
invoices o2 ON o2.inv_id <= o1.inv_id AND o1.inv_company_customer_id = o2.inv_company_customer_id
WHERE
o1.inv_company_customer_id = 1 AND
o1.inv_total > 0
GROUP BY
o1.inv_id,
o1.inv_total
HAVING
SUM(o2.inv_total) > sum_cost_total
) t
最佳答案
将cost & invoice分别分组,有02个子查询,然后join results得到最终结果
select cost_customer_id as customer_id, sum_cost_total, sum_inv_total, sum_inv_total- sum_cost_total as balance, avg_inv_date from (
select cost_customer_id, sum(cost_total) as sum_cost_total from
company_costs
group by cost_customer_id
) as c_total
inner join (
select inv_customer_id, sum(inv_total) as sum_inv_total, DATE_FORMAT(FROM_UNIXTIME(AVG(UNIX_TIMESTAMP(inv_date))), '%Y-%m-%d') AS avg_inv_date from
invoices
group by inv_customer_id
) as i_total
on c_total.cost_customer_id = i_total.inv_customer_id
你应该得到这样的结果:
在需要时使用 sum_inv_total > sum_cost_total
改善条件。
关于mysql select if sum greater 和 group by,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58449300/