[英]SQL select row containing all of the values in interval
我知道這個問題措辭不好,對不起,我真的無法用語言表達這個問題。 這是一個表示:
我有兩個表:產品和可用性。 一個產品可以有多個可用日期。 例子:
Table 1 (products):
id | name | ....
----------------------------------
1 | My product 1 | ....
2 | My product 2 | ....
Table 2 (availability):
id | productId | date
-----------------------------------------
1 | 1 | 2021-01-15
2 | 1 | 2021-01-16
3 | 1 | 2021-01-17
4 | 2 | 2021-01-15
5 | 2 | 2021-01-16
是否有一個 sql 語句,給定一個間隔,允許我們為間隔的每個元素獲取在可用性表中具有一行的產品列表?
例如,給定區間 [2021-01-15 -> 2021-01-17],請求應返回產品 1,因為它在整個期間都可用(每個元素都有一行:第 15、16 和 17) . Product2 未返回,因為它在 2021 年 1 月 17 日不可用。
有沒有辦法在 SQL 中做到這一點,還是我必須使用 PL/SQL?
任何幫助表示贊賞,謝謝
您可以使用解析 function 如下:
select p.* from
(select p.*, count(distinct a.date) over (partition by a.productid) as cnt
from products p
join availability a on a.productid = p.id
where a.date >= date '201-01-15'
and a.date < date '201-01-17' + 1 )
where cnt = date '201-01-17' - date '201-01-15' + 1
最后,想出了這個,感謝@Popeye 的啟發。
select occurence.pid from
(
select a.product_id as pid, count(distinct a.date::date) as cnt
from availability a
where a.date >= '2021-01-15'
and a.date < '2021-01-17'::date + 1
group by a.product_id
) as occurence
where cnt = '2021-01-17'::date - '2021-01-15'::date + 1;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.