SQL组按“列名”

时间:2013-11-04 20:55:02

标签: sql oracle

我似乎无法理解为什么这个查询失败了,在我的group by子句中我有我的select中的列但我仍然得到错误。为什么是这样?以下是我的询问;

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"

3 个答案:

答案 0 :(得分:2)

你需要摆脱GROUP BY中的l.cost_line,正如mti2935建议的那样,并且还要摆脱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

答案 1 :(得分:0)

我认为问题是你不应该在GROUP BY子句中使用l.cost_line,因为你在SELECT子句的聚合函数中使用了这个字段。在GROUP BY子句中尝试不使用l.cost_line,看看是否能解决问题。

答案 2 :(得分: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;