Reputation: 437
I have a query:
SELECT id, year, avg(amount) from table1
WHERE amount IS NOT NULL
INNER JOIN table2
ON table1.id = table2.id
GROUP BY id
2 Issues:
I can group by year, but It won't let me put the primary key "id" in my select statement and also group on it. Any suggestions?
In general, I'd like to get the avg amount for each id for each year and then join it with another table with id, but I want id in my returned query.
Upvotes: 0
Views: 727
Reputation: 1269933
The correct syntax is:
SELECT id, year, avg(amount)
FROM table1 JOIN
table2
ON table1.id = table2.id
WHERE amount IS NOT NULL
GROUP BY id, year;
WHERE
is a clause that follows the FROM
clause. JOIN
is an operator that works only in the FROM
clause. You will note that when I indent queries, the clauses are left justified, and the binary operators are at the end of line.
Upvotes: 0
Reputation: 2686
SELECT id, year, avg(amount) over(partition by year, order by id) from table1
INNER JOIN table2
ON table1.id = table2.id
WHERE amount IS NOT NULL
GROUP BY id, year
Upvotes: 1
Reputation: 133370
You should include also the where condition in ON clause
SELECT id, year, avg(amount) from table1
INNER JOIN table2
ON table1.id = table2.id and amount IS NOT NULL
GROUP BY id, year
and add year to group by too
Upvotes: 0
Reputation: 50064
You've got a lot of things going haywire here. Properly written your query should look something like:
SELECT table1.id, table1.year, avg(table2.amount)
FROM table1
INNER JOIN table2
ON table1.id = table2.id
WHERE amount IS NOT NULL
GROUP BY table1.id, year;
FROM
clause. They don't get combined.id
you want in the outputUpvotes: 1
Reputation: 7180
You need to qualify the 'id' column as it is present in 2 tables in your query.
SELECT table1.id, year, avg(amount) from table1
INNER JOIN table2
ON table1.id = table2.id
WHERE amount IS NOT NULL
GROUP BY table1.id, year
Upvotes: 1