表1:字段: 日期 字段a 字段b其中日期字段并不是每天都有记录,比如9月,有可能9月5日,7日等等在表1中无记录行。现需要实现用sql取出数据集,该数据集为某月份表1中所有天数的记录,比如5日,7日没记录,则取出的数据集合应该为 日期 字段a 字段b
1 1 1
2 2 2
. . .
. . .
. . .
5 null null请问在oracle里用sql语句该如何实现?
1 1 1
2 2 2
. . .
. . .
. . .
5 null null请问在oracle里用sql语句该如何实现?
----------- ---------- ----------
2005-9-2 A 90
2005-9-5 B 100
2005-9-8 D 200
2005-9-11 C 140Executed in 0.031 secondsSQL> select trunc(sysdate,'mm')+r-1 "日期",字段1,字段2 from
(select rownum r from test where rownum <= trunc(last_day(sysdate)) - trunc(sysdate,'mm') +1) n
left join
(select * from b) m
on
trunc(sysdate,'mm')+r-1 = b4;日期 字段1 字段2
----------- ---------- ----------
2005-9-1
2005-9-2 A 90
2005-9-3
2005-9-4
2005-9-5 B 100
2005-9-6
2005-9-7
2005-9-8 D 200
2005-9-9
2005-9-10
2005-9-11 C 140
2005-9-12
2005-9-13
2005-9-14
2005-9-15
2005-9-16
2005-9-17
2005-9-18
2005-9-19
2005-9-20
2005-9-21
2005-9-22
2005-9-23
2005-9-24
2005-9-25
2005-9-26
2005-9-27
2005-9-28
2005-9-29
2005-9-30 30 rows selectedExecuted in 0.219 secondsSQL>
----------- ---------- ----------
2005-9-14 1 1 1
2005-9-16 1 2 2SQL>
SQL> select d, sum(a), sum(b) from
2 (
3 select
4 trunc(d, 'dd') d, a, b
5 from test
6 union
7 select
8 trunc((select min(d) from test), 'month') + rownum - 1,
9 null,
10 null
11 from all_tables
12 where rownum <=
13 (
14 select
15 last_day(trunc(max(d), 'month')) - trunc(min(d), 'month')
16 from test
17 ) + 1
18 ) group by d order by d
19 /D SUM(A) SUM(B)
----------- ---------- ----------
2005-9-1
2005-9-2
2005-9-3
2005-9-4
2005-9-5
2005-9-6
2005-9-7
2005-9-8
2005-9-9
2005-9-10
2005-9-11
2005-9-12
2005-9-13
2005-9-14 1 1
2005-9-15
2005-9-16 2 2
2005-9-17
2005-9-18
2005-9-19
2005-9-20 D SUM(A) SUM(B)
----------- ---------- ----------
2005-9-21
2005-9-22
2005-9-23
2005-9-24
2005-9-25
2005-9-26
2005-9-27
2005-9-28
2005-9-29
2005-9-30 30 rows selectedSQL>
指的是test表中的记录要有31条以上,因为一个月最多有31天——可能是28/29/30/31。
8 trunc((select min(d) from test), 'month') + rownum - 1,
第6句ROWNUM 如何理解?