如果来自一个表的值存在于其他表中,则SQL Query打印Y.

时间:2017-01-02 13:11:29

标签: sql sql-server

新年快乐!!

我正在使用SQL Server我有三个表。 Employee,EmployeeVeteran和VeteranBranch:

    Employee
    ------------------------
    EmployeeId     Name
    ------------------------
    1001           Adams
    1002           Jacobs
    1003           Peter
    1004           Nancy

    EmployeeVeteran
    ---------------------------------
    EmployeeVeteranId    EmployeeID  BranchId
    ---------------------------------
    1                    1002        1
    2                    1004        2

    VeteranBranch
    ---------------------------------
    BranchId    BranchName
    ---------------------------------
    1           Air Force
    2           Army

我需要编写一个SQL查询来获取以下格式的数据:

    ------------------------------------------------
    EmployeeId     Name         IsVeteran     Branch
    ------------------------------------------------
    1001           Adams        N             NULL
    1002           Jacobs       Y             Air Force
    1003           Peter        N             NULL
    1004           Nancy        Y             Army

你能建议我怎么做?

3 个答案:

答案 0 :(得分:2)

您正在寻找left join。重要的是"链"他们在一起:

select e.EmployeeId, e.Name,
       (case when ev.EmployeeVeteranId is null then 'N' else 'Y' end) as IsVeteran,
       vb.BranchName
from employee e left join
     employeeveteran ev
     on ev.EmployeeVeteranId = e.EmployeeVeteranId left join
     VeteranBranch vb
     on vb.BranchId = ev.BranchId;

答案 1 :(得分:1)

切换案例声明与左连接一起使用,如下所示

SELECT 
    E.EmployeeID,
    E.Name,
    CASE ISNULL(VB.BranchName,'') WHEN '' THEN 'Y' 
    ELSE 'N' END AS IsVeteran,
    VB.BranchName AS Branch
FROM Employee E
LEFT JOIN EmployeeVeteran EV ON E.EmployeeID=EV.EmployeeID
LEFT JOIN VeteranBranch VB ON EV.BranchID=VB.BranchID

答案 2 :(得分:0)

请尝试使用代码......

Select E.EmployeeID,E.Name,Case When EV.VeteranID IS NOT NULL Then 'Y' Else 'N' END AS IsVeteran,VB.BranchName
From Employee E
LEFT JOIN EmployeeVeteran EV
On E.EmployeeID = EV.EmployeeID
LEFT JOIN VeteranBranch VB
On EV.BranchID = VB.BranchID