Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/postgresql/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
POSTGRESQL问题:如何根据列的不同状态存储和使用计算字段?_Postgresql - Fatal编程技术网

POSTGRESQL问题:如何根据列的不同状态存储和使用计算字段?

POSTGRESQL问题:如何根据列的不同状态存储和使用计算字段?,postgresql,Postgresql,我有一个名为transactions的表,其中有一列名为type,一列名为orderID,一列名为status type | orderID | status | dollar_amount __________________________________________ sale | 123 | approved | 3.23 tax | 123 | approved | 0.74 refund| 123 | approved | 3.21 sale | 456 |

我有一个名为transactions的表,其中有一列名为
type
,一列名为
orderID
,一列名为
status

type | orderID | status | dollar_amount
__________________________________________
sale  | 123   | approved | 3.23
tax   | 123   | approved | 0.74
refund| 123   | approved | 3.21
sale  | 456   | rejected | 2.98
类型
可以是
'sale'
'tax'
'return'
状态
可以是“拒绝”或“批准”

我想计算一个字段,在该字段中,我可以计算所有“销售”和“税务”交易的总和,减去
状态下所有“退款”的总和
“已批准”
,所有这些都按
订单ID进行分组

我被困在获取交易状态并在一个设置中计算它们。。。 有什么建议吗

我现在有什么

select sum(dollar_amount) as grosssale 
from transactions l 
where l.status = 'approved'
and (type = 'sale' or type = 'tax'))


我建议在表上定义一个视图,并添加一个使用窗口函数计算的列:

CREATE VIEW transaction_plus AS
SELECT orderid, dollar_amount, type, status,
       sum(dollar_amount) FILTER (WHERE type IN ('sale', 'tax') OVER w -
       sum(dollar_amount) FILTER (WHERE type = 'refund' AND status = 'apploved') OVER w
FROM transactions
WINDOW w AS (PARTITION BY orderid);

我希望我正确理解了你的公式;如果没有,请根据您的需要调整查询。

回答问题,并提供一个表或其他相关对象的
创建
语句(粘贴文本、不使用图像、不链接到外部站点),
插入样本数据的
语句(dito)以及以表格文本格式显示样本数据的所需结果。展示你已经尝试过的东西。解释失败的原因/原因。具体(错误消息、意外结果等)。编辑@stickybit