在一个表中查找值以更新另一个表

时间:2013-04-29 19:53:07

标签: join filter conditional-statements lookup

我有一个表有用户ID,另一个表有AD组;某些AD组会告诉您客户端是否是VIP,Pilot,Remote Access等组的成员。

当尝试创建一个视图来显示客户端所属的这些组中的哪一个时,我遇到了必须为每个组名创建单独的连接的问题,因为不这样做会在结果中创建重复项。

Table One
Client_ID   Client_Name
---------   ------------
A               ABC
D               DEF
G               GHI

Table Two:
Client_ID      AD_Group
---------      --------
A               I_GroupX
A               GroupY
D               B_GroupX
D               GroupZ
G               GroupY
G               GroupZ

Result Table:
Client_ID       Client_Name      VIP(X)     Pilot(Y)       RemoteAccess(Z)
---------       -----------      ------     --------        -----------
A                 ABC            I_GroupX     GroupY           Not Member
D                 DEF            Not Member   GroupY            GroupZ
G                 GHI            B_GroupX     Not Member        GroupZ

这可行,但必须为每个组创建一个而不是在一个视图中创建一个:

SELECT Client_ID,
      ,Client_Name
      ,[VIP] = CASE
       WHEN A.GroupX IS NULL THEN 'Not Member'
                             ELSE A.AD_Group
       END
  FROM Table1 LEFT OUTER JOIN 
      (SELECT [Client_ID]
             ,[AD_Group]
        FROM Table2
       WHERE  [AD_Group] LIKE '%GroupX') A 
    ON Client_ID = A.Client_ID

提前致谢

1 个答案:

答案 0 :(得分:1)

SELECT Client_ID, Client_Name,
[VIP(X)] = ISNULL((select AD_Group from Table2 where Client_Id = t1.Client_ID and AD_Group LIKE '%GroupX'), 'Not Member'),
[Pilot(Y)] = ISNULL((select AD_Group from Table2 where Client_Id = t1.Client_ID and AD_Group LIKE '%GroupY'), 'Not Member'),
[RemoteAccess(Z)] = ISNULL((select AD_Group from Table2 where Client_Id = t1.Client_ID and AD_Group LIKE '%GroupZ'), 'Not Member')
FROM Table1 t1