I have a problem as follows; Let’s say I have 3 tables like this:
tableA
ID_name | Name | |
---|---|---|
1 | Alice | xx |
2 | Betty | xx |
3 | Chris | xx |
tableB
Id_task | id_name | Tasks_submitted |
---|---|---|
1 | 1 | 1 |
2 | 2 | 1 |
3 | 1 | 1 |
4 | 2 | 1 |
5 | 1 | 1 |
tableC
Id_C | Task_count | score |
---|---|---|
1 | 0 | E |
2 | 1 | D |
3 | 2 | C |
4 | 3 | B |
5 | 4 | A |
Then I execute this query:
Select name,COUNT(Tasks_submitted) as TASKS, score
from tableA
LEFT JOIN tableB on tableA.ID_name=tableB.id_name
JOIN tableC ON (SELECT COUNT (Tasks_submitted)) = tableC.Task_count
GROUP BY tableA.ID_name
But that doesn’t work.
The result I want:
Name | TASKS | score |
---|---|---|
Alice | 3 | B |
Betty | 2 | C |
Chris | 0 | E |
Is it possible in SQL to use "SELECT COUNT" or alias as a reference to another table in the JOIN ON clause? Or is there another way to achieve the query result I desire? Many Thanks.
2
Answers
You need to aggregate the
tableB
(tasks) data in a derived table, so the count is available for the join:You have not included much of an explanation, so we do not know what the possible values for
Tasks_submitted
are. If it can only be1
thenCOUNT(*)
is slightly more efficient, as it is not null checking the column.Assuming there is an index on
tableB.id_name
, doing the aggregation on justtableB
in the derived table should be more efficient than having bothtableA
andtableB
in the derived table, but test with your data to verify either way.Here’s a db<>fiddle.