我想在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
答案 0 :(得分:2)
您可以使用FIRST_VALUE
/ LAST_VALUE
窗口函数:
CREATE TEMP TABLE e (DATE_COMPILED date, OPENING_BAL int, CLOSING_BAL int);
INSERT INTO e (opening_bal, closing_bal, DATE_COMPILED) VALUES
(5000.00, 6000.00, '2017-04-28'),
(6000.00, 9000.00, '2017-05-31'),
(9000.00, 9500.00, '2017-06-30');
SELECT
FIRST_VALUE(OPENING_BAL) OVER all_dates_asc,
LAST_VALUE(CLOSING_BAL) OVER all_dates_asc
FROM e
WINDOW all_dates_asc AS (
ORDER BY DATE_COMPILED ASC
ROWS BETWEEN UNBOUNDED PRECEDING
AND UNBOUNDED FOLLOWING
)
LIMIT 1;
┌─────────────┬────────────┐
│ first_value │ last_value │
├─────────────┼────────────┤
│ 5000 │ 9500 │
└─────────────┴────────────┘
(1 row)
答案 1 :(得分:0)
您可以尝试按所需的值排序并选择第一个结果,例如:
(SELECT * FROM reconcilation ORDER BY DATE_COMPILED::date ASC LIMIT 1)
UNION
(SELECT * FROM reconcilation ORDER BY DATE_COMPILED::date DESC LIMIT 1)
如果您只需要单列,您还可以选择所需的列,但在这种情况下,您将失去清晰度
(SELECT opening_balance FROM reconcilation WHERE council_name = 'BAKONE' ORDER BY DATE_COMPILED::date Desc LIMIT 1)
UNION
(SELECT closing_balance FROM reconcilation WHERE council_name= 'BAKONE' ORDER BY DATE_COMPILED::date ASC LIMIT 1)
由于数据按日期排序,而不是按日期时间排序,如果同一天有多个条目,查询可能会返回不准确的结果,您仍然可以按日期和ID排序,或仅按ID排序,但我会保留id out of it。
ORDER BY DATE_COMPILE::date, id ASC