SQL技术咨询:按冬季销量升序统计并列出产品
Fixing Your Winter Sales Statistics Query
Let's work through this step by step to get your query right—we'll fix the gaps in your initial code and build a reliable solution for counting winter product sales sorted from lowest to highest quantity.
First, Let's Fix the Issues in Your Initial Snippet
- You're missing a table join to connect product details from
Productswith their sales records inSales. - Using
BETWEENfor a fixed date range won't work for winter, since it spans two calendar years (e.g., December 2019 to February 2020). This would miss cross-year winter sales. - Your
GROUP BYreferences a non-existent column (sales_products.products_id)—we need to group by the actual product identifiers from theProductstable.
Correct SQL Query (MySQL Example)
This query handles cross-year winter dates, joins tables properly, counts sales, and sorts as requested:
SELECT p.product_code, p.product_name, COUNT(s.sales_code) AS Quantity FROM Products p INNER JOIN Sales s ON p.product_code = s.product_code WHERE MONTH(STR_TO_DATE(s.sales_date, '%d-%m-%Y %H:%i')) IN (1, 2, 12) GROUP BY p.product_code, p.product_name ORDER BY Quantity ASC;
Breakdown of Each Part:
- Table Join: We use
INNER JOINto linkProducts(aliased asp) withSales(aliased ass) via the sharedproduct_codefield. This ensures we only pull products that have winter sales records. If you want to include products with zero winter sales (showing0as Quantity), swapINNER JOINwithLEFT JOIN. - Date Filter:
STR_TO_DATE(s.sales_date, '%d-%m-%Y %H:%i')converts yourdd-mm-yyyy hh:mmdate string into a proper date type the database can parse.MONTH(...)extracts the month number, andIN (1,2,12)targets only January, February, and December sales—regardless of the year.
- Count Sales:
COUNT(s.sales_code)tallies the number of sales records per product (assuming eachsales_coderepresents one sale transaction). - Grouping: We group by
product_codeandproduct_nameto aggregate sales counts for each unique product. - Sorting:
ORDER BY Quantity ASCsorts results from the lowest to highest sales quantity.
Adjustments for Other Databases:
- SQL Server: Replace
MONTH(STR_TO_DATE(...))withDATEPART(MONTH, CONVERT(DATE, s.sales_date, 105))(105 is the format code fordd-mm-yyyy). - PostgreSQL: Use
EXTRACT(MONTH FROM TO_DATE(s.sales_date, 'DD-MM-YYYY HH24:MI')).
Example Output (Matching Your Expected Result):
| product_code | product_name | Quantity |
|---|---|---|
| 3334 | AAA | 55 |
| 8388 | BBB | 97 |
内容的提问来源于stack exchange,提问作者user18609967
相关产品推荐
相关产品推荐

