SQL error Unknown column in field list using multiple subquery

Issue

I’m trying to print the text based on the column. My idea was union all the count on each occupation and use a case to display it. But I’m not sure what is wrong with this code. Getting a error as sCount is not in field list. Any help is appreciated.

SELECT  CASE

        WHEN Occupation = "doctor" THEN
        CONCAT("There are a total of ", dCount, " " , Occupation, "s.")
        
        WHEN Occupation = "singer" THEN
        CONCAT("There are a total of ", sCount, " " , Occupation, "s.")
        
        END
FROM (
    SELECT * FROM (
        SELECT COUNT(Occupation) AS dCount, Lower(Occupation) AS Occupation FROM OCCUPATIONS WHERE Occupation = 'Doctor'
    UNION
        SELECT COUNT(Occupation) AS sCount, Lower(Occupation) AS Occupation FROM OCCUPATIONS WHERE Occupation = 'Singer'
    ) AS s
) AS m;

// this didnt work either
SELECT  CASE

        WHEN Occupation = "doctor" THEN
        CONCAT("There are a total of ", dCount, " " , Occupation, "s.")
        
        WHEN Occupation = "singer" THEN
        CONCAT("There are a total of ", sCount, " " , Occupation, "s.")
        
        END
FROM (
    SELECT COUNT(Occupation) AS dCount, Lower(Occupation) AS Occupation FROM OCCUPATIONS WHERE Occupation = 'Doctor'
    UNION
    SELECT COUNT(Occupation) AS sCount, Lower(Occupation) AS Occupation FROM OCCUPATIONS WHERE Occupation = 'Singer'
) AS m;

Solution

Are you trying something like this :

CREATE TABLE OCCUPATIONS  (
  Occupation varchar(100) );

INSERT INTO OCCUPATIONS  VALUES ('doctor'),('doctor'),
                                ('singer'),('singer'),
                                ('doctor'),('doctor'),
                                ('singer'),('singer'),
                                ('doctor'),('singer'),
                                ('singer'),('singer');




SELECT  CASE
        WHEN Occupation = "doctor" THEN
        CONCAT("There are a total of ", tbl.dCount, " " , Occupation, "s.") 
        WHEN Occupation = "singer" THEN
        CONCAT("There are a total of ", tbl.sCount, " " , Occupation, "s.")        
        END as total_count
FROM (          
SELECT COUNT(Occupation) AS dCount,null as sCount, Lower(Occupation) AS Occupation 
FROM OCCUPATIONS 
WHERE Occupation = 'doctor'
group by Occupation 
union 
SELECT null as tst, COUNT(Occupation) AS sCount, Lower(Occupation) AS Occupation 
FROM OCCUPATIONS 
WHERE Occupation = 'singer'
group by Occupation 
      )
as tbl ;

Result based on my demo would be:

total_count

There are a total of 5 doctors.

There are a total of 7 singers.

Demo: https://www.db-fiddle.com/f/pB6b5xrgPKCivFWcpQHsyE/28

Answered By – Ergest Basha

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published