SQL Server:自我连接-检索与where子句匹配的记录以及别名表中没有记录时

时间:2019-05-08 04:01:43

标签: sql sql-server tsql

我有一个如下表:

enter image description here

查询:

select t1.* 
from TABLE2 as t1 
left join TABLE2 as t2 on t1.itemcode = t2.itemcode 
                       and t1.warehouseid = '576' 
                       and t1.flag = 'Y' 
                       and t2.warehouseid = '276' 
                       and t2.flag = 'Y';

我有上述查询,并理解这并不完美。

对于商品代码,如果满足以下条件(t1.warehouseid ='576'和t1.flag ='Y'和t2.warehouseid ='276'和t2.flag ='Y'),我想检索从t1开始。

此外,如果t2中没有商品代码条目(例如:456对于仓库编号276不可用),那我也想从t1中检索。

期望以下输出

 123        576     Y
 456        576     Y 

对此的正确查询是什么?

编辑: 为了使帖子更清晰,

仓库ID 576是主要元素。

对于要在两个仓库ID(576,276)中存在且标记相同('Y')的项目代码,我想检索。

如果项目代码不在另一个仓库中(276),那我也要检索

对于在两个仓库ID(576,276)中都带有不同标志('Y','N')的商品代码,我不希望这样。

3 个答案:

答案 0 :(得分:1)

直接根据WHERE子句中的2个条件进行解释

select  *
from    TABLE2  t
where   warehouseid = 576
and (
        exists   -- condition 1
        (
            select  *
            from    TABLE2 x
            where   x.itemcode  = t.itemcode
            and x.warehouseid   = 276
            and x.flag      = 'Y'
        )
    or  not exists -- condition 2
        (
            select  *
            from    TABLE2 x
            where   x.itemcode  = t.itemcode
            and x.warehouseid   = 276
        )
    )

答案 1 :(得分:0)

希望这对您有用

    select t1.* from TABLE2 as t1 
     left join TABLE2 as t2 
     on t1.itemcode=t2.itemcode and t2.warehouseid='276' and t2.flag='Y';
where
     t1.warehouseid='576' and t1.flag='Y' 

答案 2 :(得分:0)

还有另一种使用row_number()的方法

    with cte as
    (select t1.*,
    row_number() over(partition by itemcode order by warehouseid desc
                     ) rn
                from TABLE2 t1
    where not exists ( select 1 from TABLE2 t2 where t1.itemcode=t2.itemcode
                                                    and t2.flag='N'
                     ) and t1.warehouseid=576
   ) select * from cte where rn=1