从不同的行中选择数据

时间:2017-02-15 07:56:06

标签: postgresql

我想在PostgreSQl中选择第一个月的期初余额和上个月的期末余额,然后现在我将收入总额作为总收入和支出总额作为同一行的总支出...这是我的

下面的数据
ID OPENING_BAL INCOME EXPENDITURE CLOSING_BAL COUNCIL_NAME DATE_COMPILED
21   5000.00   1000.00  2000.00   6000.00     BAKONE       2017-04-28
22   6000.00   1000.00  4000.00   9000.00     BAKONE       2017-05-31
23   9000.00   1500.00  2000.00   9500.00     BAKONE       2017-06-30

1 个答案:

答案 0 :(得分:3)

您可以使用窗口功能执行此操作:

SELECT DISTINCT council_name,
       first_value(opening_bal) OVER w AS opening_bal,
       sum(income) OVER w AS total_income,
       sum(expenditure) OVER w AS total_expenditure,
       last_value(closing_balance) OVER w AS closing_balance
FROM my_table
WINDOW w AS (PARTITION BY council_name ORDER BY date_compiled
             ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING);

这是对表格中整个时期的总结。如果需要,您可以添加WHERE子句来选择范围date_compiled