SQL select 包含间隔中所有值的行

SQL select row containing all of the values in interval

我知道这个问题措辞不当,对不起,我真的无法用语言表达这个问题。这是一个表示:

我有两个 table:产品和可用性。一个产品可以有多个可用日期。示例:

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 语句,在给定间隔的情况下,允许我们为间隔的每个元素获取在可用性 table 中有一行的产品列表?

例如,给定时间间隔 [2021-01-15 -> 2021-01-17],请求应该 return 产品 1,因为它在整个期间都可用(每个时间段都有一行元素:第 15、16 和 17)。 Product2 未 return 编辑,因为它在 2021 年 1 月 17 日不可用。

有没有办法在 SQL 中执行此操作,还是我必须使用 PL/SQL?

感谢任何帮助, 谢谢

您可以使用解析函数如下:

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;