[英]Error code 1111: says invalid use of group function
我正在嘗試使用來自供應商的 select Suppliers.sid 離開加入 Catalog on Suppliers.sid=Catalog.sid where Catalog.cost>avg(Catalog.cost); 但我收到錯誤代碼 1111:不確定我的數據庫發生了什么。 我對 sql 非常好,只是在讓它工作時遇到問題。
CREATE DATABASE CSC123Lab2;
USE CSC123Lab2;
CREATE TABLE Suppliers (
sid CHAR(20),
sname CHAR(20),
address CHAR(20),
pid CHAR(20)
);
CREATE TABLE Parts (
pid CHAR(20),
pname CHAR(20),
color CHAR(20),
sid CHAR(20)
);
CREATE TABLE Catalog (
sid CHAR(20),
pid CHAR(20),
cost REAL
);
ALTER TABLE Suppliers ADD PRIMARY KEY (sid);
ALTER TABLE Parts ADD PRIMARY KEY (pid);
INSERT INTO Suppliers (sid, sname, address) VALUES (1, "carvel", "1234 Main Street");
INSERT INTO Suppliers (sid, sname, address) VALUES (2, "coldstone", "5678 Pine Street");
INSERT INTO Suppliers (sid, sname, address) VALUES (3, "ralphs", "9876 Oak Street");
INSERT INTO Suppliers (sid, sname, address) VALUES (4, "Acme Widget", "4321 Maple Street");
INSERT INTO Parts (pid, pname, color) VALUES (1, "hammer", "red");
INSERT INTO Parts (pid, pname, color) VALUES (2, "screwdriver", "pink");
INSERT INTO Parts (pid, pname, color) VALUES (3, "nails", "green");
INSERT INTO Parts (pid, pname, color) VALUES (4, "screws", "teal");
INSERT INTO Catalog (sid, pid, cost) VALUES (1, 3, 32);
INSERT INTO Catalog (sid, pid, cost) VALUES (4, 1, 10);
INSERT INTO Catalog (sid, pid, cost) VALUES (4, 3, 48);
INSERT INTO Catalog (sid, pid, cost) VALUES (2, 4, 24);
select Suppliers.sid
from Suppliers
left join Catalog on Suppliers.sid=Catalog.sid
where Catalog.cost>avg(Catalog.cost);
DROP TABLE Catalog;
DROP TABLE Parts;
DROP TABLE Suppliers;
DROP DATABASE CSC123Lab2;
使用 group by 並在下一級過濾
with cte as
(select Suppliers.sid,avg(Catalog.cost) as avg_val
from Suppliers
left join Catalog on Suppliers.sid=Catalog.sid
group by Suppliers.sid
) select a.sid
from Catalog a join cte on a.sid=cte.sid
where a.cost>avg_val
我想你只想要一個 window function:
select s.sid
from Suppliers s join
(select c.*, avg(c.cost) over () as avg_cost
from Catalog c
) c
on s.sid = c.sid
where c.cost > c.avg_cost;
但是請注意,您實際上並不需要left join
。 where
子句將左連接變為inner join
。
然后,您根本不需要join
,因為sid
在兩個表中:
select c.sid
from (select c.*, avg(c.cost) over () as avg_cost
from Catalog c
) c
where c.cost > c.avg_cost;
如果您願意,可以使用子查詢來表達:
select c.sid
from Catalog c
where c.cost > (select avg(c2.cost) from catalog c2);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.