簡體   English   中英

SQL 對於表中的每個值,根據該值對另一個表執行查詢

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM