根据另一个字段的代码聚合一个字段中的多个值
我需要根据同一个表的另一个字段中的代码计算表中一个字段的多个值。
该表位于 PostgreSQL 8.3 数据库中。
表:
cod_1 | cod_2 | date | cod_sum| import
1 | 2 | 01/01/2012 | a | 1.1
1 | 2 | 01/01/2012 | a | 1.2
1 | 2 | 01/01/2012 | b | 1.1
1 | 2 | 01/01/2012 | b | 1.1
1 | 2 | 01/01/2012 | c | 1.1
1 | 2 | 01/01/2012 | c | 1.1
我需要这样的东西:
cod_1 | cod_2 |date |sum_import_a|sum_import_b|calc_import_abc(a+b-c)
1 | 2 |01/01/2012| 2.3 | 2.2 | 2.3 (2.3+2.2-2.2)
我希望你能伸出援手......
I need to calculate several values from a field in a table depending on a code in another field of the same table.
The table is in a PostgreSQL 8.3 database.
Table:
cod_1 | cod_2 | date | cod_sum| import
1 | 2 | 01/01/2012 | a | 1.1
1 | 2 | 01/01/2012 | a | 1.2
1 | 2 | 01/01/2012 | b | 1.1
1 | 2 | 01/01/2012 | b | 1.1
1 | 2 | 01/01/2012 | c | 1.1
1 | 2 | 01/01/2012 | c | 1.1
I need something like this:
cod_1 | cod_2 |date |sum_import_a|sum_import_b|calc_import_abc(a+b-c)
1 | 2 |01/01/2012| 2.3 | 2.2 | 2.3 (2.3+2.2-2.2)
I hope you can lend a hand ...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用新的窗口函数 (PostgreSQL 8.4 或更高版本)您甚至可以在没有子查询的情况下执行此操作:
但是,为了简单起见,(对于 PostgreSQL 8.3)我会像 @Adrian 演示的那样执行此操作,只是没有逻辑错误:
With the new window functions (PostgreSQL 8.4 or later) you could even do that without subquery:
For simplicity, however, (and for PostgreSQL 8.3) I would do it like @Adrian demonstrates, just without the logic error:
假设您的列集始终相同(关于值 a、b 和 c),这就是您需要的:
Supposing your column set is always the same (regarding values a, b and c), here's what you need: