尝试基于连接查找记录

时间:2021-04-22 19:32:24

标签: sql join ssms-2016

我正在尝试处理一个有点棘手的存储过程,假设我有 Table_1 与此数据:

Num1         Name1         Code1      Desc
-------------------------------------------
123B         Apple         10         Text1
123B         Apple         11         Text1
123C         Google        20         Text2

我也有一个看起来像这样的查找表:

Tbl_LookUp

Num1        Code1
-------------------
123B        10
123C        25

所以我在这个场景中尝试做的是:

从表_1 中选择数据,位置:

  1. Num1 上的 Table_1 和 Tbl_Lookup 之间存在匹配

  1. 如果 Table_1 中特定 Num1 的记录超过 1,则只返回 Table_1.Code1=Tbl_Lookup.Code1 所在的行

  2. 否则,如果 Table_1 中特定的 Num1 只有 1 条记录,那么即使 Table_1.Code1 = Tbl_Lookup.Code1 不起作用,仍然返回该记录。

期望的最终结果:

Num1         Name1         Code1      Desc
--------------------------------------------
123B         Apple         10         Text1
123C         Google        20         Text2

返回 123B,因为此 Num1 有多个记录。其中之一具有对应于 Tbl_Lookup.Code1

的 Code1

返回123C,因为虽然Code1不匹配Tbl_Lookup,但是只有一条记录,这样join也无所谓,我们还是要返回。

非常感谢任何帮助。

4 个答案:

答案 0 :(得分:1)

不确定是否有更好的方法来做到这一点。但这应该给你想要的

select t.*
from table1 t
join Tbl_LookUp l on l.Num1 = t.Num1
where t.code1 = l.code1 
or exists ( select count(1) from table1 i
           where i.Num1= t.Num1 
           group by  Num1  
           having count(Num1) = 1   )
      

答案 1 :(得分:1)

一种方法是

select t.Num1, t.Name1, t.Code1, t.Desc
from (
    select Num1, Name1, Code1, Desc, 
       count(code1) over(partition by Num1) cnt
    from Table_1 ) t
join Tbl_Lookup tl on t.Num1 = tl.Num1
    and (t.cnt = 1 or t.Code1 = tl.Code1)

答案 2 :(得分:1)

这是使用 apply 的好地方:

select t1.*
from tbl_lookup l cross apply
     (select top (1) t1.*
      from table1 t1
      where t1.num1 = l.num1
      order by (case when t.code = l.code1 then 1 else 2 end)
     );

答案 3 :(得分:1)

另一种获得所需结果的方法 - 使用 exists 确定精确查找匹配并计算 num1 的出现次数,然后允许任何计数为 1 或仅在两列上匹配超过 1 :

select num1, name1, code1, [desc]
from (
    select * , case when exists (select * from [lookup] l where l.num1 = t.num1 and l.code1 = t.code1) then 1 end lmatch, Count(*) over (partition by num1) cnt
    from t1 t 
    where exists (select * from [lookup] l where l.num1 = t.num1)
)x
where lmatch = 1 and cnt > 1 or cnt = 1;
相关问题