我有兩個簡單的表:
表格1apples_consumption
| 報告日期 | apples_consumed |
|---|---|
| 2022-01-01 | 5 |
| 2022-02-01 | 7 |
| 2022-03-01 | 2 |
表#2hotel_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 |
如果我要使用代碼撰寫此任務的解決方案,我會檢查表中的每一個report_date,apples_consumption并計算有多少訪問者的值低于/等于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
上面的查詢有效,但效率很低(我可以看到它對于較大的資料集的執行時間相對較長,順便說一下它的撰寫方式[它運行內部計數(*)查詢與外部apples_consuptions表的行數一樣多)
我正在尋找一種更有效的方法來實作這一結果,我們將非常感謝您的幫助!
uj5u.com熱心網友回復:
在您的選擇串列中放置子選擇很少是一個好主意。
加入您的表,然后使用匯總計數:
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<>在這里擺弄
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/491939.html
標籤:sql PostgreSQL 表现
下一篇:基于輪班時間的排行表
