Return SELECT 语句如果结果介于两个值之间

Return SELECT statement if result is between two values

我有两个表:

客户:

id  FirstName   LastName    Age     City
----------------------------------------
1        Joey       Blue     40  Goddard
2       Barry      Bonds     50  Gaddard
3        Mike    Schmidt     60       KC
4       Steve      Jones     45 New York

订单:

OrderId  OrderDate              CustomerID  ProductID
-----------------------------------------------------
      1 2019-08-06 12:10:02.270          1          1
      2 2019-08-06 12:10:33.690          2          1
      3 2019-08-06 12:10:44.970          2          2
      4 2019-08-06 12:10:51.910          1          1
      5 2019-08-06 12:10:52.210          1          1
      6 2019-08-06 12:10:52.657          1          1
      7 2019-08-06 12:10:53.067          1          1
      8 2019-08-06 12:11:17.340          2          1
      9 2019-08-06 12:11:23.963          2          2
     10 2019-08-06 12:11:32.063          3          2
     11 2019-08-06 12:11:38.503          3          1
     12 2019-08-06 12:11:38.790          3          1
     15 2019-08-17 19:51:45.070          2          1
     16 2019-08-17 19:52:14.207          2          2
     17 2019-08-17 19:52:14.540          2          2
     18 2019-08-17 19:52:14.923          2          2
     19 2019-08-17 19:52:31.240          1          2
     20 2019-08-17 19:52:37.363          1          2
     21 2019-08-17 19:52:38.860          1          2
     22 2019-08-17 19:52:39.213          1          2
     23 2019-08-17 19:52:39.613          1          2
     24 2019-08-17 19:52:39.997          1          2
     25 2019-08-17 19:52:40.360          1          2

我正在尝试 return 任何拥有 4 到 8 个订单的客户的名字和订单计数。

我可以加入表格并计算订单数量:

SELECT 
    Cu.FirstName, COUNT(Od.CustomerID) AS 'Customer Orders'
FROM
    Customer AS Cu
INNER JOIN 
    Orders AS Od ON Cu.id = Od.CustomerID
GROUP BY 
    Od.CustomerID, Cu.FirstName
ORDER BY 
    [Customer Orders] DESC

哪个 return 输出:

FirstName   Customer Orders
----------------------------
     Joey                12
    Barry                 8
    Mike                  3

但我不能让 BETWEEN 工作到 return(所以我只得到有 4 到 8 个订单的客户(所以我想要的输出是:)

FirstName   Customer Orders
---------------------------------
    Barry                 8

只需使用 HAVING 子句:

SELECT Cu.FirstName,COUNT(Od.CustomerID) as 'Customer Orders'
  FROM Customer as Cu
  INNER JOIN Orders as Od on Cu.id=Od.CustomerID
  GROUP BY Od.CustomerID, Cu.FirstName
 HAVING COUNT(Od.CustomerID) between 4 and 8
  ORDER BY [Customer Orders] DESC

P.S。到目前为止,我们还不知道您的 DBMS。对于某些数据库(例如 MySQL)SQL,允许在 having 子句中使用别名,例如 HAVING Customer_Orders between 4 and 8 for COUNT(Od.CustomerID) as Customer_Orders

您可以使用 having 来过滤聚合函数的结果

SELECT Cu.FirstName,COUNT(Od.CustomerID) as 'Customer Orders'
from Customer as Cu
inner join Orders as Od on Cu.id=Od.CustomerID
GROUP BY Od.CustomerID, Cu.FirstName
HAVING COUNT(Od.CustomerID) between 4 and  8 
ORDER BY [Customer Orders] DESC