在postgresql中打开和关闭不同产品的数量查询

问题描述 投票:0回答:1

我正在尝试在PostgreSQL查询中设置打开和关闭列,以便在不同产品的单独打开和关闭时输入特定的日期范围,我的第一行的开始列应该是开始日期和结束应该是(打开列+ column1 + column2 +列3)在每个日期明智的行中。

***这是我的示例数据库

Date1        Product    column1  column2   column3
01/01/2017   A          25       15        20
02/01/2017   C          10       20        20
03/01/2017   B          10       10        20
04/01/2017   C          10       10        20
05/01/2017   A          10       20        10
05/01/2017   C          5        10        20
06/01/2017   B          10       10        20
06/01/2017   A          10       10        20
06/01/2017   C          10       10        20

我在PostgreSQL *日期范围内的预期查询是04/01/2017至06/01/2017:

Date1         Product      opening  column1  column2  column3 closing
04/01/2017    C            50       10       10       20      90
05/01/2017    A            60       10       20       10      100
              C            90       5        10       20      125
06/01/2017    A            100      10       10       20      140
              B            40       10       10       20      80
              C            125      10       10       20      165
sql postgresql
1个回答
0
投票

我有一个建议,但这是在SQL服务器,我不熟悉Postresql。您可以通过任何适合于u-的循环或光标将日期范围作为@trans_date传递来运行以下查询

SELECT Date1,Product,SUM(opening.opn_qty)AS打开,SUM(column1)AS column1,SUM(column2)AS column2,SUM(column3)AS column3,SUM(closing.cls_qty)AS关闭FROM sample_table1 LEFT OUTER JOIN(SELECT (SUM(column1)+ SUM(column2)+ SUM(column3))AS opn_qty,Product FROM sample_table1 WHERE Date1 <@trans_date GROUP BY Product,Date1)open ON opening.Product = sample_table1.Product LEFT OUTER JOIN(SELECT(SUM( column1)+ SUM(column2)+ SUM(column3))AS cls_qty,Product FROM sample_table1 WHERE Date1 <= @trans_date GROUP BY Product,Date1)close ON open.Product = sample_table1.catalog_item_id WHERE sample_table1.Date1 = @trans_date GROUP BY sample_table1 .Product,Date1 ORDER BY Date1 DESC;

您可以在PostgreSQL中应用类似的逻辑。

© www.soinside.com 2019 - 2024. All rights reserved.