Reputation:
SELECT DISTINCT
t1.name as t1_name,
MAX(t1.unit) as t1_unit,
MAX(t1.id_producer_goods) AS hi_id_producer_goods,
t2.name as t2_name
FROM Table1 t1
left join Table2 t2 on t1.id_web_site=t2.id_web_site
WHERE t1.id='23'
GROUP BY t1.name
When I run the query, I get the following error:
Column 'Table2.name' is invalid in the select list because it is not contained
in either an aggregate function or the GROUP BY clause.
How to write this query?
Upvotes: 2
Views: 4276
Reputation: 4059
I don't think you need DISTINCT keyword here .
SELECT
t1.name as t1_name,
MAX(t1.unit) as t1_unit,
MAX(t1.id_producer_goods) AS hi_id_producer_goods,
t2.name as t2_name
FROM Table1 t1
left join Table2 t2 on t1.id_web_site=t2.id_web_site
WHERE t1.id='23'
GROUP BY t1.name,t2.name
Upvotes: 0
Reputation: 15387
Try this
SELECT
DISTINCT
t1.name as t1_name,
MAX(t1.unit) as t1_unit,
MAX(t1.id_producer_goods) AS hi_id_producer_goods,
t2.name as t2_name FROM Table1 hi
left join Table2 t2 on t1.id_web_site=t2.id_web_site
WHERE
t1.id='23'
GROUP BY t1.name,t2.name
You are using aggregate function with 2 columns then you need to group on both columns
Upvotes: 0
Reputation: 7244
SELECT
t1.name as t1_name,
MAX(t1.unit) as t1_unit,
MAX(t1.id_producer_goods) AS hi_id_producer_goods,
t2.name as t2_name FROM Table1 hi
left join Table2 t2 on t1.id_web_site=t2.id_web_site
WHERE
t1.id='23'
GROUP BY t1.name,t2.name
You need to group by all fields that are not used in AGG functions. etc MAX
Upvotes: 1
Reputation: 79889
The error is pretty clear, either use an aggregate function with the t2.name
or add it to the GROUP BY
, it depends on the desired results you are looking for:
SELECT
t1.name as t1_name,
t2.name as t2_name,
MAX(t1.unit) as t1_unit,
MAX(t1.id_producer_goods) AS hi_id_producer_goods
FROM Table1 hi
left join Table2 t2 on t1.id_web_site=t2.id_web_site
WHERE t1.id='23'
GROUP BY t1.name, t2.name;
The error makes sense, because it has to know which value to select from the t2.name
for each group of t1.name
? should it select the max
, min
, etc. Otherwise GROUP BY
it.
Also, remove the DISTINCT
there is no need for it with GROUP BY
.
Upvotes: 5