我有两个表一个CUSTOMERS
+-----------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-----------+--------------+------+-----+---------+-------+
| ID | int(11) | NO | PRI | NULL | |
| FIRSTNAME | varchar(50) | YES | | NULL | |
| LASTNAME | varchar(50) | YES | | NULL | |
| ADDRESS | varchar(100) | YES | | NULL | |
+-----------+--------------+------+-----+---------+-------+
和订单
+---------------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+---------------+--------------+------+-----+---------+-------+
| ID | int(11) | NO | PRI | NULL | |
| PRODUCT_NAME | varchar(100) | YES | | NULL | |
| PRODUCT_PRICE | double(10,4) | YES | | NULL | |
| DATE_ORDER | date | YES | | NULL | |
| ID_CUSTOMER | int(11) | YES | | NULL | |
| AMOUNT | int(11) | YES | | NULL | |
+---------------+--------------+------+-----+---------+-------+
我需要"获取订单总数大于所有订单平均总和的客户的名字和姓氏。不关心重复"。
我在这里尝试了
select FIRSTNAME, LASTNAME, ID,
AVG(PRODUCT_PRICE * AMOUNT)
from CUSTOMERS C
join ORDERS O
on C.ID = ID_CUSTOMER
GROUP BY FIRSTNAME, LASTNAME
HAVING AVG(PRODUCT_PRICE * AMOUNT) < (
select (PRODUCT_PRICE * AMOUNT)
from ORDERS
where C.ID = O.ID_CUSTOMER;
这不起作用。我需要一些帮助
答案 0 :(得分:2)
您需要查找子查询中所有订单的平均总和。
select
C.ID,
C.FIRSTNAME,
C.LASTNAME,
SUM(O.PRODUCT_PRICE * O.AMOUNT)
from CUSTOMERS C
join ORDERS O
on C.ID = O.ID_CUSTOMER
GROUP BY C.ID, C.FIRSTNAME, C.LASTNAME
HAVING SUM(PRODUCT_PRICE * AMOUNT) > (
select AVG(PRODUCT_PRICE * AMOUNT)
from ORDERS)
答案 1 :(得分:0)
您的代码的大部分内容都是正确的,您只需删除部分where C.ID = O.ID_CUSTOMER;
即可。这不需要计算订单商品的平均价值。
使用以下代码,您可以获得所需的输出
SELECT FIRSTNAME,LASTNAME FROM CUSTOMERS
INNER JOIN ORDERS ON CUSTOMERS.ID=ORDERS.ID_CUSTOMER
GROUP BY CUSTOMERS.ID
HAVING SUM(ORDERS.PRODUCT_PRICE*ORDERS.AMOUNT)>
(SELECT AVG(PRODUCT_PRICE*AMOUNT) FROM ORDERS)