如何根据特定条件在PostgreSQL中使用'SUM()'?用于汇总会计日记帐表中的借方和贷方
我有一个装满会计日记账的数据库。会计日记账本身有一个表(会计日记账的元数据),会计日记账行有一个表(每个账户的借方或贷方) 我有这样的数据库:如何根据特定条件在PostgreSQL中使用'SUM()'?用于汇总会计日记帐表中的借方和贷方,postgresql,Postgresql,我有一个装满会计日记账的数据库。会计日记账本身有一个表(会计日记账的元数据),会计日记账行有一个表(每个账户的借方或贷方) 我有这样的数据库: +----+---------------+--------+---------+ | ID | JOURNAL_NAME | DEBIT | CREDIT | +----+---------------+--------+---------+ | | | | | | 1 | IN
+----+---------------+--------+---------+
| ID | JOURNAL_NAME | DEBIT | CREDIT |
+----+---------------+--------+---------+
| | | | |
| 1 | INV/0001 | 100 | 0 |
| | | | |
| 2 | INV/0001 | 0 | 100 |
| | | | |
| 3 | INV/0002 | 200 | 0 |
| | | | |
| 4 | INV/0002 | 0 | 200 |
+----+---------------+--------+---------+
+--------------+--------+---------+
| JOURNAL_NAME | DEBIT | CREDIT |
+--------------+--------+---------+
| | | |
| INV/0001 | 100 | 100 |
| | | |
| INV/0002 | 200 | 200 |
+--------------+--------+---------+
我想把所有同名的日记账汇总成一个,它们的借方和贷方。所以从上表中。。。我想要一个查询,它可以生成如下内容:
+----+---------------+--------+---------+
| ID | JOURNAL_NAME | DEBIT | CREDIT |
+----+---------------+--------+---------+
| | | | |
| 1 | INV/0001 | 100 | 0 |
| | | | |
| 2 | INV/0001 | 0 | 100 |
| | | | |
| 3 | INV/0002 | 200 | 0 |
| | | | |
| 4 | INV/0002 | 0 | 200 |
+----+---------------+--------+---------+
+--------------+--------+---------+
| JOURNAL_NAME | DEBIT | CREDIT |
+--------------+--------+---------+
| | | |
| INV/0001 | 100 | 100 |
| | | |
| INV/0002 | 200 | 200 |
+--------------+--------+---------+
我试过:
SELECT DISTINCT ON (accounting_journal.id)
accounting_journal.name,
accounting_journal_line.debit,
accounting_journal_line.credit
FROM accounting_journal_line
JOIN accounting_journal ON accounting_journal.id = accounting_journal_line.move_id
ORDER BY accounting_journal.id ASC
LIMIT 3;
通过上面的查询,我得到了所有日记账和日记账行。我只需要使用上面的查询,对每个相同的会计日记帐.name
的借方和贷方进行合计
我试过使用SUM()
,但它总是卡在GROUPBY`子句中
SELECT DISTINCT ON (accounting_journal.id)
accounting_journal.name,
accounting_journal.ref,
accounting_journal_line.name,
SUM(accounting_journal_line.debit),
SUM(accounting_journal_line.credit)
FROM accounting_journal_line
JOIN accounting_journal ON accounting_journal.id = accounting_journal_line.move_id
ORDER BY accounting_journal.id ASC
LIMIT 3;
错误:
Error in query (7): ERROR: column "accounting_journal.name" must appear in the GROUP BY clause or be used in an aggregate function
LINE 2: accounting_journal.name,
我希望我能在这里得到帮助或指点我需要看的地方。谢谢 当您对普通列使用任何聚合函数时,您必须提及group by子句中的所有非聚合列 所以试试这个:
SELECT DISTINCT ON (accounting_journal.id)
accounting_journal.name,
accounting_journal.ref,
accounting_journal_line.name,
SUM(accounting_journal_line.debit),
SUM(accounting_journal_line.credit)
FROM accounting_journal_line
JOIN accounting_journal ON accounting_journal.id = accounting_journal_line.move_id
group by 1,2,3
ORDER BY accounting_journal.id ASC
LIMIT 3;
在您的查询中,您有3个非聚合列,因此您可以在group by子句中提及列号来实现它。您可以使用总和,它不需要“group by”。因此:
请参阅一个工作示例。这不是简单的
选择名称、金额(借方)、金额(贷方)。。。按名称分组代码>?