0

Just running a SQL and wrote a query with a sub query but it has returned a null value, when its not suppose too. Not to sure if anyone can help without the database but here is my query:

*This is the exercise question: 'Use an SQL statement with a sub-query to list the employee ID and full name of those employees who are managers. Use the column headings Manager ID and Manager.'

SELECT 
    ReportsTo As 'Manager ID',
    CONCAT(FirstName,' ',Lastname) As 'Manager'

FROM 
    Employees
WHERE 
    EmployeeID IN 
        (SELECT  ReportsTo 
            FROM Employees);
user3444694
  • 61
  • 3
  • 12

3 Answers3

0

Assuming I'm understanding your question, you want to return those employees that are marked as managers (denoted by the reportto column). If so, you could use EXISTS:

select employeeid, concat(firstname,' ', lastname) fullname
from employees e
where exists (
  select 1
  from employees e2
  where e.employeeid = e2.reportsto)

This will return a list of employees with their id and full name whose id exists in the reportsto field.

If you prefer the in syntax, then this should work the same:

select employeeid, concat(firstname,' ', lastname) fullname
from employees e
where employeeid in (
  select reportsto
  from employees
)
sgeddes
  • 62,311
  • 6
  • 61
  • 83
0

First, the subquery appears incorrect. You are trying to say "Grab me ReportsTo and peoples names from the Employees table where the Employee ID is equal to any of the ReportsTo fields in the same table"

You would need to change the ReportsTo in the subquery to EmployeeID. IE

SELECT 
    ReportsTo As 'Manager ID',
    CONCAT(FirstName,' ',Lastname) As 'Manager'

FROM 
    Employees
WHERE 
    EmployeeID IN 
    (SELECT  EmployeeID --Here is where i've changed the value 
        FROM Employees);

However this query in itself is no different from just simply writing:

SELECT 
    ReportsTo As 'Manager ID',
    CONCAT(FirstName,' ',Lastname) As 'Manager'

FROM 
    Employees

If you are trying to filter out your results somehow, what "Employees" records do you want to filter out? PLease give more info.

ngrashia
  • 9,869
  • 5
  • 43
  • 58
Arielhhs
  • 76
  • 1
0

User CONCATWS function istead of CONCAT which handle null value.

refer link MySQL CONCAT returns NULL if any field contain NULL

this below is sqlserver example. In sqlserver ISNULL function to handle null value

declare @Employees table(EmployeeID int, firstname varchar(50), lastname varchar(50), ReportsTo int null)

insert into @Employees values ( 1,'abc','xyz',0),( 2,'def','xyz1',1),( 3,'abc1','xyz2',null)

SELECT 
    ReportsTo As 'Manager ID',
    isnull( FirstName ,'') + '' + ISNULL(lastname,0 ) as 'Manager'
    --CONCAT(FirstName,' ',Lastname) As 'Manager'

FROM 
    @Employees
WHERE 
    EmployeeID IN 
        (SELECT  ReportsTo 
            FROM @Employees);
Community
  • 1
  • 1
Ajay2707
  • 5,690
  • 6
  • 40
  • 58