我有一个问题:
SELECT id, year, avg(amount) from table1
WHERE amount IS NOT NULL
INNER JOIN table2
ON table1.id = table2.id
GROUP BY id
2个问题:
我可以按年分组,但它不会让我把主键" id"在我的select语句中以及它上面的组。有什么建议吗?
一般情况下,我希望每年为每个ID获取平均金额,然后将其与另一个带有ID的表连接,但我想在返回的查询中使用id。
答案 0 :(得分:1)
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
答案 1 :(得分:1)
您需要对“身份证”进行限定。列,因为它出现在查询的2个表中。
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
答案 2 :(得分:1)
你在这里遇到了很多事情。正确编写您的查询应该类似于:
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
子句分开。他们没有合并。id
答案 3 :(得分:0)
正确的语法是:
SELECT id, year, avg(amount)
FROM table1 JOIN
table2
ON table1.id = table2.id
WHERE amount IS NOT NULL
GROUP BY id, year;
WHERE
是遵循FROM
子句的子句。 JOIN
是运算符,仅适用于FROM
子句。您将注意到,当我缩进查询时,子句是左对齐的,二元运算符位于行的末尾。
答案 4 :(得分:0)
您还应该在ON子句中包含where条件
SELECT id, year, avg(amount) from table1
INNER JOIN table2
ON table1.id = table2.id and amount IS NOT NULL
GROUP BY id, year
并将年份添加到群组