PostgreSQL中基于配送时效筛选产品并标记重要日期的SQL实现
PostgreSQL Query for Your Product Record Requirements
Here's a solution that uses window functions to rank your records and a CASE statement to mark the Important_date as requested:
WITH filtered_ranked_data AS ( SELECT -- Include all original table fields *, -- Assign a row number per product: prioritize smallest date_difference, then latest Purchasedate ROW_NUMBER() OVER ( PARTITION BY Product ORDER BY date_difference ASC, Purchasedate DESC ) AS record_rank FROM your_table_name -- Apply initial filter criteria WHERE date_difference < 5 AND customer_rating > 3 ) SELECT -- Select all original fields Product, Purchasedate, deliverydate, date_difference, customer_rating, -- Use CASE to mark Important_date only for the top-ranked record per product CASE WHEN record_rank = 1 THEN Purchasedate ELSE NULL END AS Important_date FROM filtered_ranked_data;
How this works:
CTE Filtering & Ranking:
- First, we filter the records to only include those where
date_differenceis less than 5 days andcustomer_ratingis above 3. - The
ROW_NUMBER()window function assigns a unique rank to each record within its product group. We order first bydate_differenceascending (to get the smallest value) and then byPurchasedatedescending (to pick the latest purchase if there's a tie in the minimum date difference).
- First, we filter the records to only include those where
CASE Statement for Important_date:
- In the final select, we use a CASE statement to set
Important_dateto thePurchasedateonly for the record with a rank of 1 (the top-priority record for each product). All other records getNULLfor this field.
- In the final select, we use a CASE statement to set
Note:
Don't forget to replace your_table_name with the actual name of your table in the database.
内容的提问来源于stack exchange,提问作者Budhaditya Bose
相关产品推荐
相关产品推荐

