在两个表中创建具有两列的视图

时间:2011-12-18 02:54:12

标签: oracle plsql oracle10g

有两个表:salesexpensessales有两列:sale_dateprice,费用表有两列:dateamount。还有view天数 年。 (Create View with 365 days

我想在此视图中添加另外两列:salesexpenses,其数据位于salesexpenses个表格。

示例:

Sales Table

sale_date   price

05-DEC-11   1,500
05-DEC-11     500
11-DEC-11     800
17-DEC-11   2,400

Expenses Table

date        amount

06-DEC-11      300
11-DEC-11      100
11-DEC-11      400
15-DEC-11    1,100

View应创建如下

date        sales   expenses

01-JAN-11    null    null
02-JAN-11    null    null
03-JAN-11    null    null
04-JAN-11    null    null
05-JAN-11    null    null

...


05-DEC-11   2,000    null
06-DEC-11    null     300
07-DEC-11    null    null
08-DEC-11    null    null
09-DEC-11    null    null
10-DEC-11    null    null
11-DEC-11     800     500
12-DEC-11    null    null
13-DEC-11    null    null
14-DEC-11    null    null
15-DEC-11    null   1,100
16-DEC-11    null    null
17-DEC-11   2,400    null

...


28-DEC-11   null     null
29-DEC-11   null     null
30-DEC-11   null     null
31-DEC-11   null     null
视图中的

salesexpenses列使用priceamount列中的saleexpenses列的总和{{ 1}}在这两个表中。

我怎么能这样做?

1 个答案:

答案 0 :(得分:0)

这应该可以帮助你:

SELECT the_day, price, amount
  FROM year_days LEFT JOIN (SELECT sale_date, SUM(price) price
                              FROM sales
                             GROUP BY sale_date) ON the_day = sale_date
                 LEFT JOIN (SELECT expense_date, SUM(expenses) amount
                              FROM expenses
                             GROUP BY expense_date) ON the_day = expense_date
 ORDER BY the_day;

THE_DAY        PRICE     AMOUNT
--------- ---------- ----------
...
01-DEC-11
02-DEC-11
03-DEC-11
04-DEC-11
05-DEC-11       2000
06-DEC-11                   300
07-DEC-11
08-DEC-11
09-DEC-11
10-DEC-11
11-DEC-11        800        500
12-DEC-11
13-DEC-11
14-DEC-11
15-DEC-11                  1100
16-DEC-11
17-DEC-11       2400
18-DEC-11
...