+ -
当前位置:首页 → 问答吧 → 请教 PostgreSQL 创建收支平衡 视图 的方法

请教 PostgreSQL 创建收支平衡 视图 的方法

时间:2011-07-05

来源:互联网

数据库中有两张表:
t_revenue 收入表,
t_payment 支出表。

SQL code

t_revenue 表结构:
id  date    name  revenue
1  2011-01-22  工资  1000
2  2011-01-22  奖金  200
3  2011-02-26  工资  2000
4  2011-02-26  奖金  500

t_payment 表结构:
id  date    name  payment
1  2011-01-01  充值  -100
2  2011-01-01  水电  -96
3  2011-02-02  充值  -200
4  2011-02-02  水电  -60
5  2011-02-26  停车  -10



现想创建一个收支平衡视图 v_balance,视图期望效果如下:
SQL code

date    revenue_sum  payment_sum  balance
2011-01-01  0      -196      -196
2011-01-22  1200     0       1200
2011-02-02  0      260      -260
2011-02-26  2500     -10      2490




请问该如何创建?谢谢!

作者: SegmentFault   发布时间: 2011-07-05

SQL code
SELECT date,
       SUM(IF(type = 'r', amount, 0) AS revenue_sum,
       SUM(IF(type = 'p', amount, 0) AS payment_sum,
       revenue_sum + payment_sum AS balance
  FROM
(
SELECT date,
       revenue AS amount,
       'r' AS type
  FROM t_revenue
 UNION ALL
SELECT date,
       payment AS amount,
       'p' AS type
  FROM t_payment
) x
 GROUP BY date
-- ORDER BY date -- 这个应该可以不用

作者: shine333   发布时间: 2011-07-05

SUM后面的括号都丢了

作者: shine333   发布时间: 2011-07-05

谢谢答复。

我运行了上面的代码,但是数据库报错:

SQL code

ERROR:  function if(boolean, numeric, integer) does not exist
LINE 2:     SUM(IF(type = 'r', amount, 0)) AS revenue_sum,
                ^
HINT:  No function matches the given name and argument types. You might need to add explicit type casts.


********** 错误 **********

ERROR: function if(boolean, numeric, integer) does not exist
SQL 状态: 42883
指导建议:No function matches the given name and argument types. You might need to add explicit type casts.
字符:22




运行的代码:
SQL code

SELECT date,
    SUM(IF(type = 'r', amount, 0)) AS revenue_sum,
    SUM(IF(type = 'p', amount, 0)) AS payment_sum,
    revenue_sum + payment_sum AS balance
FROM (
    SELECT date,
        revenue AS amount,
        'r' AS type
    FROM t_revenue
    UNION ALL

    SELECT date,
        payment AS amount,
        'p' AS type
    FROM t_payment
) x  

GROUP BY date
ORDER BY date

作者: SegmentFault   发布时间: 2011-07-05

热门下载

更多