Search code examples
sqlpostgresqlinventory-management

Get earliest value from a column with other aggregated columns in postgresql


I have a very simple stock ledger dataset.

 1. date_and_time            store_id   product_id  batch   opening_qty closing_qty inward_qty  outward_qty

 2. 01-10-2021 14:20:00         56         a          1          5          1          0            4
 3. 01-10-2021 04:20:00         56         a          1          8          5          0            3
 4. 02-10-2021 15:30:00         56         a          1          9          2          1            8
 5. 03-10-2021 08:40:00         56         a          2          2          6          4            0
 6. 04-10-2021 06:50:00         56         a          2          8          4          0            4

Output I want:

select date, store_id,product_id, batch, first(opening_qty),last(closing_qty), sum(inward_qty),sum(outward_qty)

e.g.

 1. date      store_id  product_id  batch   opening_qty closing_qty inward_qty  outward_qty
 2. 01-10-2021  56          a         1          8          1          0            7

I am writing a query using First_value window function and tried several others but not able to get the out put I want.

select 
date,store_id,product_id,batch,
FIRST_VALUE(opening_total_qty) 
    OVER(
        partition by date,store_id,product_id,batch
        ORDER BY created_at
    )  as opening__qty,
sum(inward_qty) as inward_qty,sum(outward_qty) as outward_qty 
from table
group by 1,2,3,4,opening_total_qty

Help please.


Solution

  • As your expected result is one row per group of rows with the same date, you need aggregates rather than window functions which provide as many rows as the ones filtered by the WHERE clause. You can try this :

    SELECT date_trunc('day', date),store_id,product_id,batch
         , (array_agg(opening_qty ORDER BY datetime ASC))[1] as opening__qty
         , (array_agg(closing_qty ORDER BY datetime DESC))[1] as closing_qty
         , sum(inward_qty) as inward_qty
         , sum(outward_qty ) as outward_qty
      FROM table
     GROUP BY 1,2,3,4
    

    see the test result in dbfidle.