I am trying to run the below query , I am getting ambiguity error in location column . Can anyone please explain what is the logical error here
select firstname,lastname,location,total_count,avg_sal
from employee join
(
select location,count(location),avg(salary)
from employee
group by location
) temp_table on employee.location=temp_table.location;
3
Answers
try putting employee.location in the select. Both your tables have a column called location and so the select statement doesn’t know which tables column called location you want.
Probably your issue is that the optimizer does not know from which table (
employee
or the derivedtemp_table
) each colums refers, plus you are also missing the aliases in the derived table referred in the outer query – using aliases elimiates ambiguity, try:Both the main
employee
table and the innertemp_table
have alocation
field. You need to clarify which one you want in the select list.I know it seems like it shouldn’t matter, since they the fields are guaranteed to have the same value.
They even source from the same base table. But that’s not the whole story.
To understand why, say you have a pair of rows like this:
The location in both of those fields is the same for purposes of the
GROUP BY
andON
conditional expressions, but for one of those rows the grouped (temp_table) location value will be different for purposes of theSELECT
list.Which one should you show? The database can’t just assume either way which one you mean. You have to be explicit by prefacing the column with a table name or alias.