从具有 postgresql 中其他聚合列的列中获取最早的值

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

我有一个非常简单的股票分类账数据集。

 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

我想要的输出:

select日期,store_id,product_id,批次,第一个(opening_qty),最后一个(closing_qty),总和(inward_qty),总和(outward_qty)

例如

 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

我正在使用 First_value window 函数编写查询并尝试了其他几个函数但无法获得我想要的输出。

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

请帮忙。

由于您的预期结果是每组行一行,具有相同的 date,您需要聚合而不是 window 函数,它提供与 [=12] 过滤的行一样多的行=] 子句。你可以试试这个:

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

查看dbfidle中的测试结果。