简体   繁体   English

SQL“非单组分组函数”查询错误

[英]SQL “not a single-group group function” Error on query

SELECT B.TITLE, TO_CHAR(SUM((B.COST*OI.QUANTITY)-OI.PAIDEACH), '$999.99')
AS "Profit"
FROM ORDERS O JOIN ORDERITEMS OI
on o.order# = oi.order#
JOIN BOOKS B ON OI.ISBN = B.ISBN
WHERE O.ORDER# = 1002;

THE GOAL 目标

Determine the amount of total profit generated by the book purchased on order 1002. Display the book title and profit. 确定在订单1002上购买的书籍所产生的总利润额。显示书籍标题和利润。 The profit should be formatted to display a dollar sign and two decimal places. 利润应设置为显示一个美元符号和两个小数位的格式。 Take into account that the customer might not pay the full retail price, and each item ordered can involve multiple copies. 考虑到客户可能不会支付全部零售价,并且订购的每件商品都可能涉及多个副本。

THE PROBLEM 问题

So when trying to run the stated code above I get the error "not a single-group group function" . 因此,当尝试运行上述代码时,出现错误“不是单组组函数” I've tried grouping the whole statement on order# and the title, although when I do this I get the error "FROM keyword not found where expected" . 我已经尝试将整个语句分组在order#和标题上,尽管执行此操作时会出现错误“未在期望的位置找到FROM关键字”

Well part of your problem is you are missing the GROUP BY clause: 问题的一部分是您缺少GROUP BY子句:

SELECT B.TITLE, 
  TO_CHAR(SUM((B.COST*OI.QUANTITY)-OI.PAIDEACH), '$999.99') AS "Profit"
FROM ORDERS O 
JOIN ORDERITEMS OI
  on o.order# = oi.order#
JOIN BOOKS B 
  ON OI.ISBN = B.ISBN
WHERE O.ORDER# = 1002
GROUP BY B.TITLE;

Whenever you are using an aggregate function, you need to include a GROUP BY for the columns that are in the select list but not in an aggregate function. 每当使用聚合函数时,都需要为选择列表中但不在聚合函数中的列包括GROUP BY So you have to add a GROUP BY B.TITLE to your query. 因此,您必须在查询中添加GROUP BY B.TITLE

You have a sum() in your select clause and you don't have a group by clause. 您的select子句中有sum(),而没有group by子句。 That caused your query to crash. 这导致您的查询崩溃。

You need a group by clause: 您需要一个group by子句:

SELECT B.TITLE, TO_CHAR(SUM((B.COST*OI.QUANTITY)-OI.PAIDEACH), '$999.99')
AS "Profit"
FROM ORDERS O JOIN ORDERITEMS OI
on o.order# = oi.order#
JOIN BOOKS B ON OI.ISBN = B.ISBN
WHERE O.ORDER# = 1002
group by b.title

Your problem arises because the select clause has a sum() in it. 出现您的问题是因为select子句中包含sum() This suggests an aggregation query. 这建议一个聚合查询。 Without a group by , SQL assumes that one row will be returned. 如果没有group by ,则SQL假定将返回一行。 However, you have a field b.title that is not aggregated -- hence the error. 但是,您的b.title字段未汇总-因此出现错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM