繁体   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