Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL Query error using UNION/UNION ALL and Group By

Generate the following two result sets:

1). Query an alphabetically ordered list of all names in OCCUPATIONS, immediately followed by the first letter of each profession as a parenthetical (i.e.: enclosed in parentheses). For example: AnActorName(A), ADoctorName(D), AProfessorName(P), and ASingerName(S).

2). Query the number of ocurrences of each occupation in OCCUPATIONS. Sort the occurrences in ascending order, and output them in the following format:

There are total [occupation_count] [occupation]s.

Table Name: Occupations

Total Columns: Two = 'Name' and 'Occupation', demo table is shown below:

Table: Occupations

Sample Output:

Ashely(P)
Christeen(P)
Jane(A)
Jenny(D)
Julia(A)
Ketty(P)
Maria(A)
Meera(S)
Priya(S)
Samantha(D)
There are total 2 doctors.
There are total 2 singers.
There are total 3 actors.
There are total 3 professors.

My Approach:

(SELECT NAME, '(', SUBSTRING(OCCUPATION, 1, 1), ')' 
    FROM OCCUPATIONS ORDER BY NAME) 
UNION ALL 
(SELECT COUNT(*) FROM OCCUPATIONS GROUP BY OCCUPATION ORDER BY ASEC);

Error:

ERROR 1222 (21000) at line 1: 
    The used SELECT statements have a different number of columns

Thank You!

like image 298
castel_green Avatar asked Apr 03 '16 21:04

castel_green


2 Answers

You forgot to use CONCAT function to glue your selected data

Try something like this (also see this example on sqlfiddle):

(
  SELECT CONCAT(NAME, '(', SUBSTRING(OCCUPATION, 1, 1), ')') as THETEXT, '1' as SELECTNUMBER
    FROM OCCUPATIONS
)
UNION ALL 
(
  SELECT CONCAT('There are total ', COUNT(*),' ', OCCUPATION, (IF (COUNT(*) > 1, 's',''))) as THETEXT, '2' as SELECTNUMBER
   FROM OCCUPATIONS GROUP BY OCCUPATION
)
ORDER BY SELECTNUMBER ASC, THETEXT ASC;
like image 62
alexander.polomodov Avatar answered Oct 05 '22 12:10

alexander.polomodov


I just tried on hackerrank and it works, You don't need to use Union.

select concat(name,'(',upper(substring(occupation,1,1)),')') from occupations
order by name;

select concat("There are a total of",' ',count(occupation),' ',lower(occupation),'s',".")  from occupations
group by occupation
order by count(occupation) asc;
like image 33
user2654920 Avatar answered Oct 05 '22 12:10

user2654920