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;
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0