1

我有 3 张桌子:

tblCustomer
CustomerID  CustomerName
   1         Customer 1
   2         Customer 2

tblOrder
OrderID CustomerID  OrderTypeID LoanNumber
1            1            1      98513542
2            1            1      71283527
3            1            1      10268541
4            1            1      61258965

tblOrderType
OrderTypeID    OrderTypeName
   1             Purchase
   2             Rental

现在,我要返回CustomerID、和CustomerName,客户的每个订单的数量在哪里。我正在使用以下查询:OrderTypeNameOrderCountOrderCount

SELECT tblCustomer.CustomerID, tblCustomer.customerName, tblOrderType.OrderTypeName, tblOrder.OrderID
FROM tblCustomer 
INNER JOIN tblOrder 
ON tblCustomer.CustomerID = tblOrder.CustomerID
INNER JOIN tblOrderType 
ON tblOrderType.OrderTypeID = tblOrder.OrderTypeID

它有点工作。它得到了我所要求的一切OrderCount,显然除了 。结果是这样的:

CustomerID         CustomerName      OrderTypeName     OrderID
    1               Customer 1         Purchase           1
    1               Customer 1         Purchase           2
    1               Customer 1         Purchase           3
    1               Customer 1         Purchase           4

但我正在寻找的是这个:

CustomerID         CustomerName      OrderTypeName     OrderCount
    1               Customer 1         Purchase             4

现在,我尝试Count()在不同的地方(一个)添加到查询中Count(tblOrder.OrderID),我得到一个错误tblCustomer.CustomerID is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause

这不是家庭作业。我只是不太了解 sql 和数据库交互,因为我的学校没有教过它,而且我有一个朋友正在向我抛出场景。

4

3 回答 3

3

错误消息确实告诉您问题。每当您使用聚合运算符(COUNTSUMAVG等)时,您必须告诉数据库应该如何将它们聚合在一起。您可以使用GROUP BY语句执行此操作(SQL Server 的链接,但它通常应适用于所有数据库引擎):

SELECT 
     C.CustomerID
    ,C.customerName
    ,OT.OrderTypeName
    ,COUNT(O.OrderID)
FROM tblCustomer C 
INNER JOIN tblOrder O 
   ON C.CustomerID = O.CustomerID
INNER JOIN tblOrderType OT
   ON OT.OrderTypeID = O.OrderTypeID
GROUP BY
     C.CustomerID
    ,C.customerName
    ,OT.OrderTypeName
于 2013-10-21T21:23:05.083 回答
3

您需要使用分组和聚合:

SELECT tblCustomer.CustomerID, tblCustomer.customerName, tblOrderType.OrderTypeName, 
count (tblOrder.OrderID) asOrderCOunt
FROM tblCustomer 
INNER JOIN tblOrder 
ON tblCustomer.CustomerID = tblOrder.CustomerID
INNER JOIN tblOrderType 
ON tblOrderType.OrderTypeID = tblOrder.OrderTypeID
GROUP BY
tblCustomer.CustomerID, 
tblCustomer.customerName, 
tblOrderType.OrderTypeName

如果不对未聚合的所有内容进行分组,则无法使用聚合函数。

于 2013-10-21T21:22:12.683 回答
0

试试这个,只需添加 group by 并计算分组行

SELECT tblCustomer.CustomerID, tblCustomer.customerName, 
  tblOrderType.OrderTypeName, tblOrder.OrderID, 
  COUNT(tblOrder.OrderID) as OrderCount
FROM tblCustomer INNER JOIN tblOrder 
  ON tblCustomer.CustomerID = tblOrder.CustomerID
INNER JOIN tblOrderType 
  ON tblOrderType.OrderTypeID = tblOrder.OrderTypeID
GROUP BY tblCustomer.CustomerID, tblCustomer.customerName, 
  tblOrderType.OrderTypeName
于 2013-10-21T21:23:32.337 回答