SQL,连接两个表并选择最大值

时间:2018-02-12 03:43:54

标签: sql oracle-sqldeveloper

我有两张桌子

customers_bought:
       PID        SID   QUANTITY
---------- ---------- ----------
      3289         11         12
     74591         11         10
     74591         12          1
     74591         23          1
     74591         31          1
     88331         13         21
     88331         31         48

customers:
       PID NAME               
---------- --------------------
      3289 George              
     88331 Alice               
     74591 Jane                
     10234 Able  

我需要做的就是列出购买单一类型三明治的客户。我还需要显示客户名称,pid,sid和数量。这是SQL,当然它比听起来更复杂。我不确定如何加入我在下面的两个结果,这是我设法做的:

Code:
Select C.pid, C.name, CB.sid, CB.quantity
From customers C
Inner Join customers_bought CB
On CB.PID = C.PID;

Result: 
       PID NAME                        SID   QUANTITY
---------- -------------------- ---------- ----------
      3289 George                       11         12
     74591 Jane                         11         10
     74591 Jane                         12          1
     74591 Jane                         23          1
     74591 Jane                         31          1
     88331 Alice                        13         21
     88331 Alice                        31         48

Code: 
  Select CB.sid, MAX(CB.Quantity)
  From customers_bought CB
  Group By CB.sid

Result:
       SID                        MAX(CB.QUANTITY)
---------- ---------------------------------------
        11                                      12
        13                                      21
        31                                      48
        23                                       1
        12                                       1

1 个答案:

答案 0 :(得分:1)

试试这个

 Select
C.pid, C.name, CB.sid, ms.MaxQuentity
From customers C
Inner Join customers_bought CB
On CB.PID = C.PID
INNER JOIN
(
Select 
CB.sid,
MAX(CB.Quantity)  AS MaxQuentity
  From customers_bought CB
  Group By CB.sid
 )  ms ON ms.sid = CB.sid  AND ms.MaxQuentity = CB.QUANTITY 

您可以在Fiddle

中找到示例代码