【问题标题】:Average and latest value using BigQuery SQL使用 BigQuery SQL 的平均值和最新值
【发布时间】:2021-12-22 12:04:10
【问题描述】:

我有一些这样的数据:

Product Price Date
Product A 1.00 2021-11-01
Product A 2.00 2021-11-02
Product B 3.00 2021-11-01
Product B 4.00 2021-11-02

我需要一张表中每种产品的平均价格和最新价格,所以它应该如下所示:

Product Avg(Price) Latest(Price)
Product A 1.50 2.00
Product B 3.50 4.00

总而言之,我只需要将这些组合到查询中:

SELECT  Price  FROM MyTable
where Date = (select max(Date) FROM MyTable)
group by Product

SELECT  Avg(Price) FROM MyTable
group by Product

如何编写才能正常工作?

【问题讨论】:

    标签: sql database google-bigquery


    【解决方案1】:

    考虑以下方法

    select distinct product, 
      avg(price) over prod as avg_price, 
      first_value(price) over(prod order by date desc) latest_price
    from mytable
    window prod as (partition by product)   
    

    如果应用于您问题中的样本数据 - 输出是

    【讨论】:

    • 这很好用。非常感谢
    • 请考虑投票并接受答案然后:o)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-18
    • 1970-01-01
    • 2021-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多