Saturday, February 25, 2012

Returning results Left Outer Join with Conditions

I have a SELECT Statement that I am using that is pulling from two tables. There won't always be results in the second table so I made a LEFT OUTER JOIN. The problem I am having is that I need to have three conditions in there:

WHERE (employee.emp_id = @.emp_id)AND (request.requested_time_taken ='FALSE')AND (request.request_end_date >=GETDATE()))

The two conditions from the request table are causing the entire query to return NULL as the value. I need help trying get a value whether or not there are any results in the request table.

Here is the full select statement:

SELECT (SELECTSUM(ISNULL(request.request_duration,'0'))AS Expr1FROM employeeLEFTOUTER JOIN requestAS requestON employee.emp_id = request.emp_idWHERE (employee.emp_id = @.emp_id)AND (request.requested_time_taken ='FALSE')AND (request.request_end_date >=GETDATE()))AS dayspendingFROM employeeAS employee_1LEFTOUTER JOIN requestAS request_1ON employee_1.emp_id = request_1.emp_idWHERE (employee_1.emp_id = @.emp_id)GROUP BY employee_1.emp_id, employee_1.emp_begin_accrual, employee_1.emp_accrual_rate, employee_1.emp_fname, employee_1.emp_minitial, employee_1.emp_lname

Null values are ignored in some T-SQL aggregate function such as SUM/AVG, so you can move the ISNULL function to outer:

SELECT (SELECT ISNULL(SUM(request.request_duration),0))AS Expr1...

|||

Sounds like this is what you want:

SELECT ISNULL((SELECT SUM(ISNULL(request.request_duration,'0'))AS Expr1
FROM employeeLEFTOUTER JOIN
requestAS requestON employee.emp_id = request.emp_id
WHERE (employee.emp_id = @.emp_id)AND (request.requested_time_taken ='FALSE')AND (request.request_end_date >=GETDATE())) ,0)
AS dayspending
FROM employeeAS employee_1LEFTOUTER JOIN
requestAS request_1ON employee_1.emp_id = request_1.emp_id

WHERE (employee_1.emp_id = @.emp_id)
GROUP BY employee_1.emp_id, employee_1.emp_begin_accrual, employee_1.emp_accrual_rate, employee_1.emp_fname, employee_1.emp_minitial,
employee_1.emp_lname

No comments:

Post a Comment