SQL在视图中使用“左连接”添加列

时间:2014-07-17 08:11:22

标签: sql sql-server sql-server-2008

我有一个表格,我希望根据另一个带有where子句的表添加列IS_TRUE

即:我有一个名为Employee的表,我有另一个名为Manager的表,现在我想根据以下内容在表IS_True中插入/添加Employee列:

 A.ID = B.ID where ((A.Name Is Not Null) and (B.ID is null))

寻找单个视图来执行此操作而不复制表Employee中的数据。

Employee

ID|Name|Salary
 1|B   |333
 3|B   |333
 4|B   |333
 1|B   |333

Manager

ID  |Name
 1  |A
 3  |B
 4  |B
Null|A

结果:

ID|Name|Salary|IS_True
 1|B   |333   |YES
 3|B   |333   |NO
 4|B   |333   |NO
 1|B   |333   |YES

非常感谢您的帮助

2 个答案:

答案 0 :(得分:0)

SELECT    a.*, 
          CASE WHEN a.name IS NOT NULL AND b.id IS NULL 
               THEN 'YES' 
               ELSE 'NO' 
          END AS is_true
FROM      employee a
LEFT JOIN (SELECT DISTINCT id FROM manager) b ON a.id = b.id

答案 1 :(得分:0)

试试这个:在join

中添加一个where子句
SELECT    a.*, 
          CASE WHEN a.name IS NOT NULL AND b.id IS NULL 
               THEN 'YES' 
               ELSE 'NO' 
          END AS is_true
FROM      employee a
LEFT JOIN (SELECT DISTINCT id FROM manager) b ON a.id = b.id
where b.name is null