我有两个表,一个包含订单信息,另一个包含订购事件信息,示例结构如下:
订单表:
merchant_id | order_id | 金额订单日期 | |
---|---|---|---|
1111111 | 23456 | 100 | 2021-07-01//tr>|
1111111 | 789012 | 50 | 2021-07-20|
1111111 | 642443 | 75 | 2021-08-12 |
将event
上的条件添加到联接(而不是where(:
select o.merchant_id, extract(month from o.order_date) as order_month, count(o.order_id) as order_count, sum(o.order_amount) as order_sum, count(e.order_id) as expiry_count, sum(e.amount) as expiry_sum
from orders o
left join events e on e.order_id = o.order_id
and e.event = 'EXPIRY'
where o.merchant_id = '111111'
and o.order_date >= '2021-07-01'
group by o.merchant_id, order_month
order by o.merchant_id, order_month
如果在where子句中对外部联接表设置条件,则强制联接表现为内部联接(就像删除了left
关键字一样(。