如果在product_costs.start_date小于product_revenue.start_date的地方没有找到product_costs.amount,我如何将product_costs.amount默认为0?
我在https://dbfiddle.uk/PM2nCk5R下面创建了一个fiddle,其中包含一个create脚本和查询
查询如下:
SELECT
YEAR(product_revenues.revenue_date) AS revenueYear,
MONTH(product_revenues.revenue_date) AS revenueMonth,
SUM(product_revenues.amount) AS totalRevenue,
COALESCE(SUM(product_costs.amount), 0) AS totalCost,
SUM(product_revenues.amount - COALESCE(product_costs.amount, 0)) AS totalProfit
FROM product_revenues
LEFT JOIN product_costs
ON product_costs.start_date <= product_revenues.revenue_date
AND product_costs.start_date = (
SELECT MAX(start_date)
FROM product_costs
WHERE start_date <= product_revenues.revenue_date
)
WHERE product_revenues.team_id = 1
AND product_costs.team_id =1
AND product_revenues.stripe_product_id ='prod_1234'
AND product_costs.stripe_product_id ='prod_1234'
AND product_revenues.revenue_date BETWEEN NOW() - INTERVAL 12 MONTH AND NOW()
GROUP BY revenueMonth, revenueYear
ORDER BY revenueMonth ASC;
字符串
的位子不是
产品成本
| ID|团队ID|量|条带产品标识|开始日期|
| --|--|--|--|--|
| 1 | 1 | 1000 |产品编号:1234| 2023-08-01 2023-08-01|
产品收入表
| ID|团队ID|量|条带产品标识|收入日期|
| --|--|--|--|--|
| 1 | 1 | 1000 |产品编号:1234| 2023-07-05 2023-07-05|
| 2 | 1 | 1000 |产品编号:1234| 2023-09-01 2023-09-01|
| 3 | 1 | 1000 |产品编号:1234| 2023-10-01 2023-10-01|
预期结果
| 收入年份|收入月份|总收入|总成本|总利润|
| --|--|--|--|--|
| 2023 | 07 | 1000 | 0 | 1000 |
| 2023 | 09 | 1000 | 600 | 400 |
| 2023 | 10 | 1000 | 600 | 400 |
所以收入id 1没有成本,因为没有比它更早的成本记录。但是id 2和3将归因于成本id 1。我认为左连接返回所有记录,但我的查询被限制为只返回2和3收入id。
1条答案
按热度按时间b4qexyjb1#
如果在WHERE子句中引用LEFT JOIN表,则它实际上将其转换为INNER JOIN。