Thursday, January 15, 2015

SQL: Top 3 records

SQL: Select Top 3 Records + Sum of Quantity






SELECT Pr1.model, Pr1.type, COUNT(*) num FROM Product Pr1 JOIN Product Pr2 ON Pr1.type = Pr2.type AND Pr1.model >= Pr2.model GROUP BY Pr1.type, Pr1.model HAVING COUNT (*) <= 3 ORDER BY type, model



Assuming SQL Server, I might use:
SELECT TOP(5) ProductID, SUM(Quantity) AS TotalQuantity
FROM order_items
GROUP BY ProductID
ORDER BY SUM(Quantity) DESC;
This returns the top 5 best-selling Products.
---
 In (Select Top 3 [UnitsInStock] From Products Where _
[CategoryID]=[Categories].[CategoryID] Order By [UnitsInStock] Desc)

---

SQL SERVER – Tips from the SQL Joes 2 Pros Development Series – Many to Many Relationships – Day 8 of 35

http://support.microsoft.com/kb/153747://support.microsoft.com/kb/153747CC: ACC: How to Create a Top N Values per Group QueryHow to Create a Top N Values per Group Query

No comments:

Post a Comment