简体   繁体   中英

Query with subquery needs to return all rows from original query (even when subquery comes back empty)


I am trying to write an SQL query that returns the maximum value scored on a test per employee, with each test in its own column.
So far, I've come up with:

SELECT E.id, 
       Concat(E.firstname, ' ', E.middlename, ' ', E.lastname) AS FullName, 
       score1.maxscore, 
       score2.maxscore 
FROM   employees AS E, 
       (SELECT empid, 
               Max(Cast(score AS DECIMAL)) AS MaxScore 
        FROM   filledsoc 
        WHERE  socid = '87bf5fba-5702-4304-869c-8707956d34d0' 
        GROUP  BY empid) AS score1, 
       (SELECT empid, 
               Max(Cast(score AS DECIMAL)) AS MaxScore 
        FROM   filledsoc 
        WHERE  socid = '340363d9-e9a2-478b-b819-d3a56d337561' 
        GROUP  BY empid) AS score2 
WHERE  E.id = score1.empid 
       AND E.id = score2.empid 

This is just a testquery, the final query will be built dynamically. My problem is that the query only returns results where all columns have a value.
If one of the subquerys comes back empty, the employee is skipped alltogether.
What I need is a query that returns all rows from table 'employees', and fills in score1.maxscore and score2.maxscore only when it exists. IF it doesn't '0' or nothing would be fine...

Any help on this would be appreciated.

Michel

SELECT E.ID, CONCAT(E.FirstName, ' ', E.MiddleName, ' ', E.LastName) AS FullName, 
(
  SELECT MAX(CAST(F1.Score AS DECIMAL))
  FROM FilledSOC AS F1
  WHERE F1.SocID = '87bf5fba-5702-4304-869c-8707956d34d0' 
  AND E.ID = F1.EmpID
) AS Score_1,
(
  SELECT MAX(CAST(F2.Score AS DECIMAL))
  FROM FilledSOC AS F2
  WHERE F2.SocID = '340363d9-e9a2-478b-b819-d3a56d337561' 
  AND E.ID = F2.EmpID
) AS Score_2
FROM Employees AS E

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM