I need to get the following data from Orders
table in Northwind
database using SQL (SQL Server to be exact):
CustomerID
) who placed at least 3 orders within the interval of 6 months ( OrderDate
). So for the following data the query should return 1
==========================
| CustomerID | OrderDate |
==========================
| 1 | 2000-1-1 |
--------------------------
| 1 | 2000-1-5 |
--------------------------
| 1 | 2000-4-30 |
--------------------------
| 2 | 2000-1-1 |
--------------------------
| 2 | 2000-5-30 |
--------------------------
SELECT N1.CustomerID, COUNT(N2.OrderDate) FROM Northwind N1
INNER JOIN Northwind N2
ON N1.CustomerID=N2.CustomerID
AND N1.OrderDate<=Dateadd(MONTH, 6, N2.OrderDate)
GROUP BY N1.CustomerID
HAVING COUNT(N2.OrderDate)>=3
请尝试以下操作:
SELECT OrderDate, CustomerID FROM orders GROUP BY OrderDate HAVING COUNT(CustomerID) >= 3 ORDER BY COUNT(CustomerID) DESC
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.