【问题标题】:POSTGRESQL: How to update column from resulted table?POSTGRESQL:如何更新结果表中的列?
【发布时间】:2020-02-22 22:57:56
【问题描述】:

为了根据与其他表的通用 ID 提取数据,我应用了 Select 查询以便我可以计算:creditdebitbalance强>:

SELECT account_id as account_id,account_move_line.account_id as id, 
    COALESCE(SUM(debit),0) - COALESCE(SUM(credit), 0) as balance,
    COALESCE(SUM(debit), 0) as expense_income, 
    COALESCE(SUM(debit), 0) as debit, COALESCE(SUM(credit), 0) as credit 
FROM account_move as account_move_line__move_id,account_move_line
WHERE account_id IN (SELECT id FROM account_account WHERE user_type_id IN (SELECT id from account_account_type WHERE internal_group IN ('expense','income')))  
    AND ("account_move_line"."move_id"="account_move_line__move_id"."id") 
    AND (("account_move_line__move_id"."state" = 'posted')  ) 

GROUP BY account_id,account_move_line.account_id

我得到的结果是完美的:

我想要实现的是用结果 Table 中没有 0 值的贷方和借方填充 expense_income 列。目前我只能通过使用 as 来填补第一名,我认为这不是一种方式。我也关注了一些帖子来梳理这些逻辑,但我失败了。我也为糟糕的英语道歉。

我关注的帖子:

https://dba.stackexchange.com/questions/153174/postgresql-update-table-row-values-by-grouped-column

https://dba.stackexchange.com/questions/153174/postgresql-update-table-row-values-by-grouped-column

【问题讨论】:

  • 您有 COALESCE(SUM(debit), 0) as expense_income 在您的情况下返回正确的数据。你没有在这里参与credit 专栏。那么你的问题是什么?
  • 我想用 dredit 和 debit 值填写expense_income 列
  • COALESCE(SUM(debit), 0) as fee_income , COALESCE(SUM(credit), 0) as fee_income 一起我得到错误 fee_income 已经被这样使用了
  • 如果我在查询中同时写上上述注释,则会出现错误:psycopg2.ProgrammingError: column "expense_income" 指定了不止一次
  • 或者如果我为具有值的借方和贷方分配字符串值会怎样

标签: postgresql


【解决方案1】:

如果我正确理解,您需要在借方和贷方之间使用greatest 值。如果是这样,那么你可以使用这个:

SELECT account_id as account_id,account_move_line.account_id as id, 
COALESCE(SUM(debit),0) - COALESCE(SUM(credit), 0) as balance,
greatest(COALESCE(SUM(debit), 0), COALESCE(SUM(credit), 0)) AS expense_income,


CASE WHEN COALESCE(SUM(debit),0) > COALESCE(SUM(credit), 0) THEN 'debit'
ELSE 'credit' END AS from_where_the_value_comming,

COALESCE(SUM(debit), 0) as debit, COALESCE(SUM(credit), 0) as credit 
FROM account_move as account_move_line__move_id,account_move_line
WHERE account_id IN (SELECT id FROM account_account WHERE user_type_id IN (SELECT id from account_account_type WHERE internal_group IN ('expense','income')))  
    AND ("account_move_line"."move_id"="account_move_line__move_id"."id") 
    AND (("account_move_line__move_id"."state" = 'posted')  ) 

GROUP BY account_id,account_move_line.account_id

【讨论】:

  • 是的,这就是我想要的。是否也可以从值出现的位置给出列名?例如借方为零,贷方为 102,因此在输出中费用收入从列中获得值 102:贷方
  • 如果我还在尝试,那就太好了
  • 有可能吗?如果您可以添加一列并放置一个字符串值,告诉您从哪一列获得最大值,那就太好了
  • 您需要更改列名吗?那么你需要动态 sql,但我想再添加一列,它检测值从哪里开始。
  • 还有一件事可以仅通过“from_where_the_value_comming”而不是 account_id 和 account_move_line.account_id 来分组吗?那些结果将有一个摘要显示仅指示借方和贷方,那就太好了
猜你喜欢
  • 2019-02-25
  • 2012-11-25
  • 1970-01-01
  • 2023-01-22
  • 1970-01-01
  • 2016-08-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多