我有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
,OrderTypeName
和OrderCount
,其中OrderCount
是客户每个订单中有多少订单。我正在使用以下查询:
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和数据库的相互作用,因为它没有在我的学校里教过,而且我有一个朋友在向我投掷场景。
答案 0 :(得分: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
如果不对未聚合的所有内容进行分组,则无法使用聚合函数。
答案 1 :(得分:3)
错误消息确实告诉您该问题。每当您使用聚合运算符(COUNT
,SUM
,AVG
等)时,您必须告诉数据库应如何将它们聚合在一起。您使用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
答案 2 :(得分:0)
试试这个,只需添加分组依据并计算分组行数
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