根据条件选择列 SQL Server

DoA*_*rNa 0 sql-server

我有这样的情况:

SELECT 
   fName, 
   lName
FROM employee as e
join payroll as p ON p.frn_employeeid = e.employeeId
Run Code Online (Sandbox Code Playgroud)

对于employeeId = 2(WHERE e.employeeId = 2)我还想在select子句payCheck上添加另一列

 SELECT 
   fName, 
   lName,
   payCheck (this column should show on the report ONLY if employeeId = 2)
FROM employee as e
join payroll as p ON p.frn_employeeid = e.employeeId
Run Code Online (Sandbox Code Playgroud)

我感谢任何有助于实现这一目标的帮助。

注意:我知道我可以做的一件事是使用两个查询,然后检查是否 employeeId =2 运行查询 1 否则运行查询 2 。我正在寻找是否可以只使用一个“SMART”查询

Joh*_*uet 5

案例陈述将为您提供您想要的:

SELECT fName, lName,
    CASE
        WHEN e.employeeid = 2
            THEN payCheck
        ELSE
            ''
    END AS Paycheck
FROM employee as e
    JOIN payroll as p ON p.frn_employeeid = e.employeeId
Run Code Online (Sandbox Code Playgroud)

要完全排除该列,请使用 IF THEN 语句:

IF (employeeid = 2)
    SELECT fname, lname, paycheck
    FROM employee as e
        JOIN payroll as p ON p.frn_employeeid = e.employeeId
ELSE
    SELECT fname, lname
    FROM employee as e
        JOIN payroll as p ON p.frn_employeeid = e.employeeId
Run Code Online (Sandbox Code Playgroud)