表: Orders+---------------+------+| Column Name | Type |+---------------+------+| order_id | int || product_id | int || quantity | int || purchase_date | date |+---------------+------+order_id 是该表的主键。该表中的每一行都包含订单 ID、购买的产品 ID、数量和购买日期。编写一个 SQL 查询,获取连续两年订购三次或三次以上的所有产品的 id。以任意顺序返回结果表。查询结果格式示例如下。示例 1:输入:Orders 表:+----------+------------+----------+---------------+| order_id | product_id | quantity | purchase_date |+----------+------------+----------+---------------+| 1 | 1 | 7 | 2020-03-16 || 2 | 1 | 4 | 2020-12-02 || 3 | 1 | 7 | 2020-05-10 || 4 | 1 | 6 | 2021-12-23 || 5 | 1 | 5 | 2021-05-21 || 6 | 1 | 6 | 2021-10-11 || 7 | 2 | 6 | 2022-10-11 |+----------+------------+----------+---------------+输出:+------------+| product_id |+------------+| 1 |+------------+解释:产品 1 在 2020 年和 2021 年都分别订购了三次。由于连续两年订购了三次,所以我们将其包含在答案中。产品 2 在 2022 年订购了一次。我们不把它包括在答案中。来源:力扣(LeetCode)链接:https://leetcode.cn/problems/products-with-three-or-more-orders-in-two-consecutive-years
#测试数据Create table If Not Exists Orders (order_id int, product_id int, quantity int, purchase_date date);insert into Orders (order_id, product_id, quantity, purchase_date) values ('1', '1', '7', '2020-03-16');insert into Orders (order_id, product_id, quantity, purchase_date) values ('2', '1', '4', '2020-12-02');insert into Orders (order_id, product_id, quantity, purchase_date) values ('3', '1', '7', '2020-05-10');insert into Orders (order_id, product_id, quantity, purchase_date) values ('4', '1', '6', '2021-12-23');insert into Orders (order_id, product_id, quantity, purchase_date) values ('5', '1', '5', '2021-05-21');insert into Orders (order_id, product_id, quantity, purchase_date) values ('6', '1', '6', '2021-10-11');insert into Orders (order_id, product_id, quantity, purchase_date) values ('7', '2', '6', '2022-10-11');
withtmp as (selectproduct_id,year(purchase_date) purchase_yearfrom Ordersgroup by product_id,year(purchase_date)having count(1) >= 3)selecta.product_idfrom tmp ainner join tmp bon a.product_id = b.product_idand a.purchase_year = b.purchase_year + 1group by a.product_id;

文章转载自跟强哥学SQL,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。




