[英]SQL group by “column name”
I cant seem to see why this query is failing, in my group by clause I have the columns that are in my select yet im still getting the error. 我似乎无法看到为什么这个查询失败,在我的group by子句中我有我的选择中的列但我仍然得到错误。 Why is this?
为什么是这样? Below is my query;
以下是我的查询;
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;
getting this error 得到这个错误
SQL Error: ORA-00937: not a single-group group function
00937. 00000 - "not a single-group group function"
You need to get rid of the l.cost_line in the GROUP BY, as mti2935 suggests, and also get rid of the max() function -- you can't use multiple aggregate functions like this. 您需要摆脱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 http://sqlfiddle.com/#!2/fdbba1/6
I think the problem is that you should not have l.cost_line in the GROUP BY clause, because you are using this field in an aggregate function in the SELECT clause. 我认为问题是你不应该在GROUP BY子句中使用l.cost_line,因为你在SELECT子句的聚合函数中使用了这个字段。 Try it without l.cost_line in the GROUP BY clause, and see if that solves the problem.
在GROUP BY子句中尝试不使用l.cost_line,看看是否能解决问题。
If you want the max value, you have to wrap it all up in subquery, take a look: 如果你想要最大值,你必须将它全部包装在子查询中,看看:
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;
Edit if you are using Oracle, you can make it simpler: 编辑如果您使用的是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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.