可以使用 SQL
查询来找到仅在 2019 年春季(1 月 1 日到 3 月 31 日)销售的产品,并且没有在其他时间销售的产品。
解决方案:
WITH SpringSales AS (
SELECT DISTINCT product_id
FROM Sales
WHERE sale_date BETWEEN '2019-01-01' AND '2019-03-31'
),
OtherSales AS (
SELECT DISTINCT product_id
FROM Sales
WHERE sale_date < '2019-01-01' OR sale_date > '2019-03-31'
)
SELECT p.product_id, p.product_name
FROM Product p
JOIN SpringSales ss ON p.product_id = ss.product_id
LEFT JOIN OtherSales os ON p.product_id = os.product_id
WHERE os.product_id IS NULL;
解释:
-
SpringSales
:找出在 2019 年春季(1 月 1 日到 3 月 31 日)销售的产品product_id
。 -
OtherSales
:找出在 2019 年春季之外(春季之前或之后)销售的产品product_id
。 -
连接
Product
表,并筛选仅在SpringSales
里 但不在OtherSales
里的产品。
这样就能确保查询结果只包含 2019 年春季才售出的产品。