I’m a my SQL beginner, I need to know how to display the results from 3 queries that are different in row-count. They’ll be querying the same table. Example table:
Scores
NAME | SCORE
jack | 1
mike | 3
kate | 2
able | 1
jill | 2
seth | 1
the 3 single select statements look like this:
SELECT name as Ones
FROM scores
WHERE score = 1
SELECT name as Twos
FROM scores
WHERE score = 2
SELECT name as Threes
FROM scores
WHERE score = 3
Separately the results to each query would give different row counts, but I want them in columns as below:
Ones | Twos | Threes
______________________________
jack | mike | kate
able | jill |
seth | |
Whether there’s a blank space or a null in the gaps I wouldn’t mind.
2
Answers
As you can accept even empty spaces or nulls, you can use UNION ALL like this:
to obtain what you asked for.
You can only use union all with tables with the same structure, in this case 3 columns each with the same names.
Final result is
Use
row_number()
for each score class.Have cnt derived table that returns the total number of rows.
LEFT JOIN
the score classes.Demo: https://dbfiddle.uk/CQiMcs6v