将一个表的一列与其他表的数据相匹配

时间:2011-12-19 14:43:42

标签: sql-server database sql-server-2008 join

我有2个表 - table1和table2。 table1如下:

ID
A01
A02
A03
A04
A05

table2如下:

DeptID  Name        ID
5       groupA      A01
5       groupA      A03
5       groupA      A04
5       groupB      A02
5       groupB      A04
5       groupB      A05

表3:

Codename    DisplayName
groupA      Humti
groupB      Dumpti

我希望输出为:

DeptID  Name         ID    Result
5       Humpti       A01   1
5       Humpti       A02   0
5       Humpti       A03   1
5       Humpti       A04   1
5       Humpti       A05   0
5       Dumpti       A01   0
5       Dumpti       A02   1
5       Dumpti       A03   0
5       Dumpti       A04   1
5       Dumpti       A05   1

这里,groupA附有3个ID。 A01,A03,A04。因此,对于这些,输出中的结果列的值为1.但是对于A02,A05 groupA没有关联,因此Result列值为0.只有我们需要记住的是groupA将与table1的所有ID进行比较。

编辑:所有解决方案都运行得非常好,但是我可以根据表3中的值将'groupA'替换为'Humpti'和'groupB'替换为'Dumpti'吗?

谢谢..

3 个答案:

答案 0 :(得分:2)

SELECT t2.deptId, t2.name, table1.id, CASE WHEN table2.id IS NULL THEN 0 ELSE 1 END result
FROM table1, (SELECT distinct deptId, group from table2) t2
LEFT OUTER JOIN table2 ON t2.name = table2.name AND t2.ID = table1.ID

编辑,针对您更改的问题:

SELECT t2.deptId, table3.name, table1.id, CASE WHEN table2.id IS NULL THEN 0 ELSE 1 END result
FROM table1, table3, (SELECT distinct deptId, name from table2) t2
LEFT OUTER JOIN table2 ON t2.name = table2.name AND t2.ID = table1.ID
WHERE table3.codename = t2.name

答案 1 :(得分:1)

此查询将返回您想要的数据集。这些要求有点奇怪,所以当你扩展做其他事情时它可能不起作用:

select 
    sub.*,
    result = case when t.ID is null then 0 else 1 end
from 
    (
    select distinct
        t2.DeptID,
        t2.Name,
        t1.ID
    from
        table1 t1,
        table2 t2
) sub
left join table2 t on sub.ID = t.ID and sub.name = t.name

答案 2 :(得分:1)

SELECT ddn.DeptID
     , ddn.Name
     , did.ID
     , CASE WHEN t2.id IS NOT NULL 
              THEN 1 
              ELSE 0 
       END AS Result
FROM 
     table1 AS did
  CROSS JOIN
    ( SELECT DISTINCT 
          DeptID
        , Name
      FROM table2
    ) AS ddn
  LEFT JOIN table2 AS t2 
    ON  t2.ID = did.ID
    AND t2.DeptID = ddn.DeptID
    AND t2.Name = ddn.Name