0

我似乎看不出为什么这个查询失败了,在我的 group by 子句中,我有我选择的列,但我仍然收到错误。为什么是这样?以下是我的查询;

SELECT c.customer_first_name, c.customer_last_name, MAX(SUM(cost_line))
FROM customers c LEFT OUTER JOIN orders o USING(customer_numb)
LEFT OUTER JOIN order_lines l USING (order_numb)
GROUP BY c.customer_first_name, c.customer_last_name
ORDER BY customer_numb;

收到此错误

SQL Error: ORA-00937: not a single-group group function
00937. 00000 -  "not a single-group group function"
4

3 回答 3

2

正如 mti2935 所建议的那样,您需要摆脱 GROUP BY 中的 l.cost_line,并且还要摆脱 max() 函数——您不能像这样使用多个聚合函数。

SELECT c.customer_first_name, c.customer_last_name, SUM(cost_line)
FROM customers c LEFT OUTER JOIN orders o USING(customer_numb)
LEFT OUTER JOIN order_lines l USING (order_numb)
GROUP BY c.customer_first_name, c.customer_last_name
ORDER BY customer_numb;

http://sqlfiddle.com/#!2/fdbba1/6

于 2013-11-04T21:03:25.867 回答
0

我认为问题在于您不应该在 GROUP BY 子句中包含 l.cost_line,因为您在 SELECT 子句的聚合函数中使用了此字段。在 GROUP BY 子句中不带 l.cost_line 试试看,看看是否能解决问题。

于 2013-11-04T20:58:15.667 回答
0

如果你想要最大值,你必须将它全部包装在子查询中,看看:

SELECT c.customer_first_name, c.customer_last_name, SUM(cost_line)
FROM customers c LEFT OUTER JOIN orders o USING(customer_numb)
LEFT OUTER JOIN order_lines l USING (order_numb)
GROUP BY c.customer_first_name, c.customer_last_name
HAVING SUM(cost_line) = (
  SELECT MAX(sum_cost_line)
    FROM
    (SELECT SUM(cost_line) sum_cost_line
      FROM customers c LEFT OUTER JOIN orders o USING(customer_numb)
        LEFT OUTER JOIN order_lines l USING (order_numb)
      GROUP BY c.customer_first_name, c.customer_last_name) a
  )
ORDER BY customer_numb;

编辑如果您使用的是 Oracle,则可以使其更简单:

SELECT c.customer_first_name, c.customer_last_name, SUM(cost_line)
    FROM customers c LEFT OUTER JOIN orders o USING(customer_numb)
    LEFT OUTER JOIN order_lines l USING (order_numb)
    GROUP BY c.customer_first_name, c.customer_last_name
    HAVING SUM(cost_line) = (
      SELECT MAX(SUM(cost_line))
          FROM customers c LEFT OUTER JOIN orders o USING(customer_numb)
            LEFT OUTER JOIN order_lines l USING (order_numb)
          GROUP BY c.customer_first_name, c.customer_last_name
      )
    ORDER BY customer_numb;
于 2013-11-04T21:05:16.260 回答