-1

我是一名试图做一些 SQL Server 2008 的开发人员,但我被卡住了。

我有以下两张表

表格1

Local Area   | ManagerID  
 ABC-SDF-LKJ | 1234  
 ABC-KJH-GHJ | 4321  
 XZY-TRS-YEU | 4321  
 XZY-BFG-GFH | 6789  
 INT-HSL-DSL | 6789  

表 2

Region | ManagerID  
 ABC   | 4321  
 INT   | 5764  
 XZY   | 8647

我需要创建一个查询,该查询将返回 a 的所有行ManagerId。如果 aManagerId存在于表 2 中,则它应该返回表 1 中它们是管理器的所有行,以及表 1 中以它们管理器的区域开头的所有行。

鉴于上面的数据ManagerId = 4321应该返回

ABC-SDF-LKJ  
ABC-KJH-GHJ  
XZY-TRS-YEU  

虽然ManagerId = 8647应该返回

XZY-BFG-GFH  
XZY-TRS-YEU  

并且ManagerId = 1234应该返回

ABC-SDF-LKJ  

有谁知道如何做到这一点?

4

2 回答 2

2

JOIN可以在任意表达式上,而不是 a ,LIKE我会使用LEFT([Local Area], 3). 将返回, while 中LEFT JOIN列出的那些区域。Table2for 的条件t1.ManagerId = xxxx将返回Table1与 in 不匹配的值Table2,例如 for ManagerID = 1234

SELECT
  [Local Area]
FROM
  Table1 t1
  -- Matches the Region back to the Local Area
  LEFT JOIN Table2 T2 ON LEFT(t1.[Local Area], 3) = t2.Region
WHERE
  -- For those which have no Region match in Table2
  t1.ManagerId = 1234
  -- And to get the Table1 records which start with the Region from Table2
  OR t2.ManagerId = 1234

这是一个演示:http ://sqlfiddle.com/#!3/ca497/4

于 2013-03-10T23:18:08.377 回答
1

这个怎么样:

SELECT *
FROM Table1 T1, Table2 T2
WHERE T1.ManagerID = T2.ManagerID 
OR T1.[Local Area] LIKE T2.Region + '%'

第一个条件照顾同一个经理,第二个条件照顾地区/地区。

Sql 小提琴在这里

于 2013-03-10T23:23:26.177 回答