我有一个问题。我一直在尝试查询以获得项目中使用的最大部分,但它显示的是倍数。所以对于P1,它应该只显示Nut 700,而P6应该只显示Cog 500
使用的查询是:
SELECT Distinct t1.J#, t1.P#, t1.pname, MAX(t1.qty) AS Most_Used
FROM ((SELECT J#, P.P#, P.pname, qty
FROM SPJ, P
WHERE (P.P# = SPJ.P#)
GROUP BY P.pname, J#, P.P#, SPJ.QTY)) t1
GROUP BY t1.J#, t1.P#, t1.Pname;
但我保留了这个答案:
J# P# pname Most_Used
j1 p1 Nut 200
j1 p3 Screw 400
j3 p3 Screw 200
j3 p6 Cog 300
j4 p1 Nut 700
j4 p2 Bolt 100
j4 p3 Screw 500
j4 p4 Hammer 800
j4 p5 Cam 400
j4 p6 Cog 500
j5 p3 Screw 600
j5 p5 Cam 500
j6 p3 Screw 400
j7 p3 Screw 800
j7 p5 Cam 100
j7 p6 Cog 300
有什么想法吗?
谢谢!
答案 0 :(得分:1)
你可以设置一个由J#分区的row_number()并按qty desc排序,然后只得到row_number = 1;
with rn as
(
select J#, P.P#, P.pname, qty,
row_number() over (partition by J# order by qty desc) as rnum
from SPJ
inner join P
on P.P# = SPJ.P#
)
SELECT J#, P#, name, qty as MostUsed
FROM rn
WHERE rnum = 1;