【问题标题】:Trying to look up records based on a join尝试基于联接查找记录
【发布时间】:2021-07-17 01:19:21
【问题描述】:

我正在尝试处理一个有点棘手的存储过程,假设我有 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

所以我在这种情况下想要做的是:

从 Table_1 中选择数据 WHERE:

  1. Table_1 和 Num1 上的 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没关系,我们还是要返回。

非常感谢任何帮助。

【问题讨论】:

    标签: sql join ssms-2016


    【解决方案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   )
          
    

    【讨论】:

      【解决方案2】:

      一种方法是

      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)
      

      【讨论】:

        【解决方案3】:

        这是使用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)
             );
        

        【讨论】:

          【解决方案4】:

          获得所需结果的另一种方法 - 确定与 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;
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2016-12-09
            • 2013-09-21
            相关资源
            最近更新 更多