我有两个简单的表:
表#1apples_consumption
report_date | apples_consuming | 2022-01-01 | 5 |
---|---|
2022-02-01 | 7 |
2022-03-01 | 2 |
在选择列表中添加子选择是非常不明智的。
连接表,然后使用聚合计数:
select a.report_date, count(v.visitor_id) as visitors_count, a.apples_consumed
from apples_consumption a
left join hotel_visitors v
on a.report_date
between v.check_in_date
and coalesce(v.check_out_date, '9999-12-31')
group by a.report_date, a.apples_consumed
order by a.report_date;
db<此处小提琴>此处小提琴>