根据条件SQL Server选择一列

时间:2021-07-19 22:51:50

I have a situation like this:

我有这样的情况:

SELECT 
   fName, 
   lName
FROM employee as e
join payroll as p ON p.frn_employeeid = e.employeeId

For employeeId = 2 (WHERE e.employeeId = 2) I also want to add another column on the select clause payCheck

对于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

I appreciate any help on achieving this.

我很感激有助于实现这一目标。

Note: I know that one thing I can do is use two queries and then check if employeeId =2 run let say query 1 else run query 2 . I am looking if there is a away to use only one "SMART" query

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

1 个解决方案

#1


4  

The Case Statement would give you what you want:

案例陈述会给你你想要的东西:

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

To exclude the column entirely, use the IF THEN statements:

要完全排除列,请使用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

#1


4  

The Case Statement would give you what you want:

案例陈述会给你你想要的东西:

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

To exclude the column entirely, use the IF THEN statements:

要完全排除列,请使用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