Home > database >  Average and latest value using BigQuery SQL
Average and latest value using BigQuery SQL

Time:11-10

I have some data like this:

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

I need the avgearge price and latest price for each product in one table so it should look like this:

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

To sum up, I just need to combine these to queries:

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

and

SELECT  Avg(Price) FROM MyTable
group by Product

How can I write this to work properly?

CodePudding user response:

You may use the following which uses row_number to help determine the latest price in a subquery.

SELECT
    Product,
    AVG(Price) as avg_price,
    MAX(
        CASE WHEN rn=1 THEN Price END
    ) as latest_price
FROM (
    SELECT 
        *,
        ROW_NUMBER() OVER (PARTITION BY Product ORDER BY Date DESC) rn
    FROM
        my_table
) t
GROUP BY Product;
product avg_price latest_price
Product A 1.5 2
Product B 3.5 4

enter image description here

  • Related