DoArNa
DoArNa

Reputation: 532

Select a column based on a condition SQL Server

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

 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

Upvotes: 0

Views: 5006

Answers (1)

John Pasquet
John Pasquet

Reputation: 1842

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 (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

Upvotes: 5

Related Questions