SQL - 查询未定义区间内的记录
SQL - Query records within an undefined interval
我需要使用 SQL(确切地说是 SQL 服务器)从 Northwind
数据库中的 Orders
table 获取以下数据:
- 查找在以下时间内至少下了 3 个订单的所有客户 (
CustomerID
)
间隔6个月(OrderDate
).
因此,对于以下数据,查询应该 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
我需要使用 SQL(确切地说是 SQL 服务器)从 Northwind
数据库中的 Orders
table 获取以下数据:
- 查找在以下时间内至少下了 3 个订单的所有客户 (
CustomerID
) 间隔6个月(OrderDate
).
因此,对于以下数据,查询应该 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