Sql 清点后如何计算平均值?

Sql 清点后如何计算平均值?,sql,amazon-web-services,amazon-athena,Sql,Amazon Web Services,Amazon Athena,清点后我想取平均数 以下是我当前的查询: SELECT product_id, COUNT(DISTINCT shop_id) AS shops, year, month, day FROM X GROUP BY product_id, year, month, day 但是现在,我想取商店的平均值。我尝试过类似的方法,但我得到了一个错误:invalidrequestexception SELECT product_id

清点后我想取平均数

以下是我当前的查询:

SELECT product_id,
         COUNT(DISTINCT shop_id) AS shops,
         year,
         month,
         day
FROM X
GROUP BY  product_id, year, month, day
但是现在,我想取商店的平均值。我尝试过类似的方法,但我得到了一个错误:invalidrequestexception

SELECT product_id,
         AVG(COUNT(DISTINCT shop_id) AS shops) as avg_shops,
         year,
         month,
         day
FROM X
GROUP BY  product_id, year, month, day
试试下面这样

with cte as
(
SELECT product_id,
         COUNT(DISTINCT shop_id) AS shops,
         year,
         month,
         day
FROM X
GROUP BY  product_id, year, month, day
) select product_id,
         AVG(shops) AS  as avg_shops,
         year,
         month,
         day
FROM cte
GROUP BY  product_id, year, month, day 
试试下面这样

with cte as
(
SELECT product_id,
         COUNT(DISTINCT shop_id) AS shops,
         year,
         month,
         day
FROM X
GROUP BY  product_id, year, month, day
) select product_id,
         AVG(shops) AS  as avg_shops,
         year,
         month,
         day
FROM cte
GROUP BY  product_id, year, month, day 

如果只需要平均值,请使用子查询:

SELECT AVG(shops)
FROM (SELECT product_id, COUNT(DISTINCT shop_id) AS shops
      FROM X
      GROUP BY product_id, year, month, day
     ) x

如果只需要平均值,请使用子查询:

SELECT AVG(shops)
FROM (SELECT product_id, COUNT(DISTINCT shop_id) AS shops
      FROM X
      GROUP BY product_id, year, month, day
     ) x

样本数据和期望的结果会有帮助。样本数据和期望的结果会有帮助。我应该删除查询末尾的X吗?@zineda。它是一个表别名。没有必要删除它。@GordonLinoff-我认为如果你把或作为制表符,它会更清晰-尽管Oracle出于某种原因完全无法理解这种语法@维拉斯。我从不将as用于表别名,只用于列别名。@zineda-如果删除它,查询将无法工作。查询的第一部分也可以写为SELECT AVGx.shops FROM SELECT…-看看我的小提琴。尝试删除它并查看-SQL Server的错误消息信息不是很丰富,但例如PostgreSQL和MySQL,它会告诉您该错误:FROM中的子查询必须有别名-请自己尝试并查看!我应该删除查询末尾的X吗?@zineda。它是一个表别名。没有必要删除它。@GordonLinoff-我认为如果你把或作为制表符,它会更清晰-尽管Oracle出于某种原因完全无法理解这种语法@维拉斯。我从不将as用于表别名,只用于列别名。@zineda-如果删除它,查询将无法工作。查询的第一部分也可以写为SELECT AVGx.shops FROM SELECT…-看看我的小提琴。尝试删除它并查看-SQL Server的错误消息信息不是很丰富,但例如PostgreSQL和MySQL,它会告诉您该错误:FROM中的子查询必须有别名-请自己尝试并查看!