[英]SQL For each value from a table, execute a query on another table depending on that value
我有两个简单的表:
表#1 apples_consumption
报告日期 | apples_consumed |
---|---|
2022-01-01 | 5 |
2022-02-01 | 7 |
2022-03-01 | 2 |
表 #2 hotel_visitors
访客 ID | 登记日期 | 离开日期 |
---|---|---|
1 | 2021-12-01 | 2022-02-01 |
2 | 2022-01-01 | 无效的 |
3 | 2022-02-01 | 无效的 |
4 | 2022-03-01 | 无效的 |
我的目的是得到一个表格,显示酒店的游客数量与当时消费的苹果数量之间的比率。
对于上面的示例,所需的查询输出应如下所示:
报告日期 | 访客数 | apples_consumed |
---|---|---|
2022-01-01 | 2 -->(访客#1,#2) | 5 |
2022-02-01 | 3 -->(访客#1、#2、#3) | 7 |
2022-03-01 | 3 -->(访客#2、#3、#4) | 2 |
如果我要使用代码编写此任务的解决方案,我会检查apples_consumption
表中的每个report_date
并计算有多少访问者的check_in_date
低于/等于该report_date
并且还有check_out_date
= NULL 或check_out_date
大于/等于report_date
我想出了这个查询:
select
ac.report_date,
ac.apples_consumed,
(
select count(*)
from hotel_visitors hv
where
hv.check_in_date <= ac.report_date and
(hv.check_out_date is null or hv.check_out_date >= ac.report_date
) as visitors_count
from
apples_consumptions ac
order by
ac.report_date
上面的查询有效,但效率很低(我可以看到它对于较大数据集的执行时间相对较长,顺便说一下[它运行内部 count(*) 查询与外部apples_consuptions
表具有的行数一样多)
我正在寻找一种更有效的方法来实现这一结果,我们将非常感谢您的帮助!
在您的选择列表中放置子选择很少是一个好主意。
加入您的表,然后使用汇总计数:
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<> 在这里摆弄
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.