错误#1111 - 无效使用组功能

时间:2017-03-28 00:46:27

标签: sql

编辑 - 我在XAMPP工作

我正在为学校做作业,这是我给出的数据库:

customers(customerName, city, customerNumber)

orders(customerNumber, orderNumber)

orderdetails(orderNumber, priceEach, quantityOrdered)

我正在尝试查询按总价值(priceEach * quantityOrdered)排列最大订单的客户的名称,并且我要求至少使用一个嵌套查询。

以下是我相信应该是正确的答案:

SELECT customername
FROM orderdetails 
INNER JOIN orders
on orderdetails.orderNumber = orders.orderNumber
INNER JOIN customers
on orders.customerNumber = customers.customerNumber
WHERE sum(priceEach*quantityOrdered) = (SELECT 
    max(sum(priceEach*quantityOrdered))
    FROM orderdetails
    INNER JOIN orders
    on orderdetails.orderNumber = orders.orderNumber
    INNER JOIN customers
    on orders.customerNumber = customers.customerNumber
    GROUP by orderdetails.orderNumber)
GROUP by orderdetails.orderNumber
ORDER by sum(priceEach*quantityOrdered) DESC

然而,当我输入它时,我收到错误"#1111 - 无效使用群组功能"我不能为我的生活找出原因。感谢

编辑 - 即使我从查询中删除了所有GROUP BY和ORDER BY行,我仍然会收到相同的错误。我认为这与我打电话' max'和'总和'在嵌套查询SELECT中,但我不完全确定。

2 个答案:

答案 0 :(得分:0)

使用GROUP BY时,SELECT中的所有字段必须位于聚合函数中或包含在GROUP BY子句中。

这个怎么样:

SELECT customername, SUM(orderTotal)
FROM customers 
INNER JOIN (SELECT priceEach*quantityOrdered AS orderTotal, customers.customerNumber AS customerNumber
            FROM orderdetails 
            INNER JOIN orders 
            ON orderdetails.orderNumber = orders.orderNumber
            INNER JOIN customers ON orders.customerNumber = customers.customerNumber) sub 
            ON sub.customerNumber = customers.customerNumber
GROUP by customername
ORDER by SUM(orderTotal) DESC

答案 1 :(得分:0)

试试这个......

  

并且要求我使用至少一个嵌套查询。

交叉申请将获得带有customernumber的最大销售额以返回主查询。

销售应按客户编号分组

SELECT
  customername, y.TotalSales
FROM customers a
cross apply
(
select top 1 x.TotalSales,x.customerNumber from
(SELECT
  SUM(priceEach * quantityOrdered) [TotalSales], c.customerNumber
FROM orderdetails
INNER JOIN orders
  ON orderdetails.orderNumber = orders.orderNumber
INNER JOIN customers c
  ON orders.customerNumber = c.customerNumber
GROUP BY c.customerNumber)
) x order by x.totalSales desc
) y on y.customerNumber = a.customerNumber

或订单级别的最大值,按客户编号分组,订单编号

SELECT
  customername, y.totalsales, y.ordernumber
FROM customers a
cross apply
(
select top 1 x.TotalSales,x.customerNumber,x.ordernumber from
(SELECT
  SUM(priceEach * quantityOrdered) [TotalSales], c.customerNumber,ordernumber
FROM orderdetails
INNER JOIN orders
  ON orderdetails.orderNumber = orders.orderNumber
INNER JOIN customers c
  ON orders.customerNumber = c.customerNumber
GROUP BY c.customerNumber,ordernumber)
) x order by x.totalSales desc
) y on y.customerNumber = a.customerNumber