簡體   English   中英

SQL-如何連接3個表,但只能按兩個表中的列分組

[英]SQL- how to join 3 tables but only group by columns from two

我正在嘗試將下面的3個表連接在一起,但是我只想按customer_ID分組在前2個表中,如何實現?
換句話說,我使用的第三個表只是消除記錄。 非常感謝!

表格1

customer_ID  product_No  
 100          ABC001
 100          ABC111
 100          ABC112 
 200          ABC002

表2

product_No   Amount
 ABC001        10
 ABC002        50
 ABC111        60
 ABC112        70

表3

Valid_Product  Desc
 ABC001         Y
 ABC111         Y

我可以通過執行表1和表2的連接來確定

select 
    t1.product_No, Max(t2.amount)
from 
    t1, t2
where 
    t1.product_No = t2.product_No
group by 
    customer_ID

現在,我如何在同一查詢中加入表3,並僅獲取客戶100的ABC111值,因為這是具有最大金額的有效產品?

因此結果將為Customer_ID 100 Amount 60 。目標是獲得某個客戶下某個產品的最大數量(僅當該產品位於第3個表中且帶有desc Y時)。

如果您想為每個客戶提供最大數量的有效產品,請使用row_number()

select *
from (select t1.*, t2.amount,
             row_number() over (partition by t1.customer_id t2.amount desc) as seqnum
      from t1 join
           t2
           on t1.product_No = t2.product_No join
           t3
           on t3.Valid_Product = t1.product_No
     ) t
where seqnum = 1;

它只是另一個t3.desc和對t3.desc過濾的WHERE子句。 似乎您不需要投影中的T3列。

select t1.customer_ID, Max(t2.amount)
from t1
     join t2
     on t1.product_No = t2.product_No
     join t3
     on t1.product_No = t3.valid_product
where t3.desc = 'Y'
Group by t1.customer_ID

順便說一句,您會注意到我使用ANSI 92連接語法編寫了查詢。 Oracle從9i(至今已有20年)以來一直對此提供支持,並且確實確實使查詢更易於閱讀。

對於您的輸出示例,簡單的聚合函數和聯接就足夠了

select t1.*,t2.Amount from table1 t1 join

 (
 select * from table2 t2 where amount in
   ( 
    select max(Amount) as amt
   from table2 inner join table3 t3 on 
    t2.product_No=t3.Valid_Product

   )  
  ) t2 on t1.product_No=t2.product_No

您想知道表3中是否存在產品。我們使用EXISTSIN檢查SQL中是否存在產品。

select 
  t1.customer_id, max(t2.amount)
from t2
left join t2 on  t2.product_no = t1.product_no
where t1.product_no in (select product_no from t3 where desc = 'Y')
group by t1.customer_id
order by t1.customer_id;

不要加入,僅在查找表時是否存在條目。

請嘗試使用row_number()在下面

select * from 
(select customer_ID,t1.product_No, t2.amount, row_number() over (partition by customerid order by amount desc) as rn
from t1 inner join t2
where t1.product_No = t2.product_No)a
inner join table3 on a.product_no = Valid_Product
where rn=1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM