我正在做一个作业,在其中我创建了三个表,即“项目”,“零件”和“使用”。这些表的结构如下:
SQL> CREATE TABLE PROJECT
2 (
3 PNO VARCHAR2(5) PRIMARY KEY,
4 PNAME VARCHAR2(15) NOT NULL,
5 CITY VARCHAR2(15) NOT NULL
6 );
SQL> CREATE TABLE PART
2 (
3 PID VARCHAR2(5) PRIMARY KEY,
4 PNAME VARCHAR2(15) NOT NULL,
5 COLOR VARCHAR2(15) NOT NULL
6 );
SQL> CREATE TABLE USE
2 (
3 PNO VARCHAR2(5),
4 PID VARCHAR2(5),
5 QTY NUMBER CHECK(QTY >5 AND QTY<100),
6 FOREIGN KEY(PNO) REFERENCES PROJECT,
7 FOREIGN KEY(PID) REFERENCES PART,
8 PRIMARY KEY(PNO,PID)
9 );
我想写一个查询来找出使用最多产品的项目名称。
我能够编写以下查询,该查询返回每个项目使用的零件数量。
SQL> SELECT PNO, SUM(QTY)
2 FROM USE
3 GROUP BY PNO;
PNO SUM(QTY)
----- ----------
P4 205
P1 95
P2 95
P3 20
答案 0 :(得分:0)
您可以在下面尝试-
select * from
(
SELECT PNO, SUM(QTY) as totalqty
FROM USE
GROUP BY PNO order by SUM(QTY) desc
)A where rownum=1
答案 1 :(得分:0)
尝试如下
with cte as (
SELECT PNO, SUM(QTY) as q
FROM USE
GROUP BY PNO
) select * from cte where cte.q= (select max(q) from cte)
答案 2 :(得分:0)
我们可以在此处尝试使用RANK
来捕获所有并列第一的联系:
WITH cte AS (
SELECT p.PNAME, SUM(u.QTY) AS QTY,
RANK() OVER (ORDER BY SUM(u.QTY) DESC) rnk
FROM PROJECT p
INNER JOIN USE u
ON p.PNO = u.PNO
GROUP BY p.PNO, p.PNAME
)
SELECT PNAME, QTY
FROM cte
WHERE rnk = 1
ORDER BY PNAME;