leetcode 2292 連續兩年訂購商品超過多少次的問題.
方法1 :
SELECT distinct o.product_id FROM ( SELECT product_id, year(purchase_date) year, dense_rank() over(partition by product_id order by year(purchase_date)) rk FROM Orders GROUP BY product_id, year(purchase_date) HAVING count(*) >= 3) o GROUP BY o.product_id, o.year-o.rk HAVING count(o.year) >= 2 方法2:
# Write your MySQL query statement below select distinct product_id from ( select product_id, purchase_year-rn as sub_year from ( select product_id, purchase_year, row_number() over (partition by product_id order by purchase_year) as rn from ( select product_id, year(purchase_date) as purchase_year from Orders group by product_id,purchase_year having count(*)>=3 -- 這一層是連續n年 大于購買三個的數量 ) t1 ) t2 group by product_id, sub_year having count(*)>=2 --- 這一層是至少連續兩年的意思. ) t3 作者:Sleepy NightingalemKj 鏈接:https://leetcode.cn/problems/products-with-three-or-more-orders-in-two-consecutive-years/solutions/2757982/lian-xu-lei-wen-ti-de-qiu-jie-si-lu-by-s-cmyj/ 來源:力扣(LeetCode) 著作權歸作者所有。商業轉載請聯系作者獲得授權,非商業轉載請注明出處。
| product_id | YEAR | rk | COUNT(a.order_id) |
| ---------- | ---- | -- | ----------------- |
| 1 | 2020 | 1 | 3 |
| 1 | 2021 | 2 | 3 |
| 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 | YEAR | rk |
| ---------- | ---- | -- |
| 1 | 2020 | 1 |
| 1 | 2021 | 2 |
| 2 | 2022 | 1 |
編寫解決方案,獲取連續兩年訂購三次或三次以上的所有產品的 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 年訂購了一次。我們不把它包括在答案中。

浙公網安備 33010602011771號