"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > SQL query of top 5 best-selling products in each store

SQL query of top 5 best-selling products in each store

Posted on 2025-04-13
Browse:397

How to Find the Top 5 Best-Selling Items per Store Using SQL?

Finding Top N Sold Items for Each Group Using SQL

Problem Statement:

Given a table with sales records, including the UPC code of each item sold, sale date, store ID, and total dollar sales, the objective is to retrieve the top 5 sold items for each store in a single SQL query.

Solution:

Using the Common Table Expression (CTE) syntax, we can create a temporary table named 's' to rank the top items within each store based on total dollar sales. Subsequently, we can select the top 5 items for each store using a row number filter.

;WITH s AS (
  SELECT StoreID, UPCCode, tds, rn = ROW_NUMBER()
  OVER (PARTITION BY StoreID ORDER BY tds DESC)
  FROM 
  (
    SELECT StoreID, UPCCode, tds = SUM(TotalDollarSales)
    FROM Sales
    GROUP BY StoreID, UPCCode
  ) AS s2
)
SELECT StoreID, UPCCode, TotalDollarSales = tds
FROM s
WHERE rn 

Explanation:

  • The subquery s2 calculates the sum of TotalDollarSales for each combination of StoreID and UPCCode.
  • The CTE s creates a ranking column, rn, to determine the row number for each item within each store based on total dollar sales.
  • The outer query selects the top 5 items from the CTE for each store, ordered by TotalDollarSales in descending order.
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3