我有以下Oracle SQL查询结果:
TDATE OPEN Closed
19/05/15 1 1
20/05/15 0 1
26/05/15 2 0
27/05/15 1 0
28/05/15 2 0
例如,我想从5月19日至30日查询。
我想得到的结果是:
TDATE OPEN Closed
19/05/15 1 1
20/05/15 0 1
21/05/15 0 0
22/05/15 0 0
23/05/15 0 0
24/05/15 0 0
25/05/15 0 0
26/05/15 2 0
27/05/15 1 0
28/05/15 2 0
29/05/15 0 0
30/05/15 0 0
如果查询在日期范围内,则不存在的记录将返回0和0表示打开和关闭。
任何帮助都将不胜感激。
答案 0 :(得分:1)
一个带有零的空表,所有日期都可以作为
INSERT INTO empytable
(SELECT TRUNC(@firstdat + (ROWNUM - 1)) dat, 0, 0
FROM DUAL CONNECT BY ROWNUM <= @days)
然后您可以将结果加载到此表中,否则将它们合并。
占位符firstdat
应该是添加工作的日期。
答案 1 :(得分:0)
在Oracle中,使用CTE,
WITH table_ (TDATE, OPEN, Closed) AS (
SELECT to_date('19/05/15', 'dd/mm/yy'), 1, 1 from dual UNION ALL
SELECT to_date('20/05/15', 'dd/mm/yy'), 0, 1 from dual UNION ALL
SELECT to_date('26/05/15', 'dd/mm/yy'), 2, 0 from dual UNION ALL
SELECT to_date('27/05/15', 'dd/mm/yy'), 1, 0 from dual UNION ALL
SELECT to_date('28/05/15', 'dd/mm/yy'), 2, 0 from dual),
--------------
-- End of data preparation
--------------
arr_table as (
select to_date('19/05/15', 'dd/mm/yy') + level - 1 dummy_date
from dual
connect by ROWNUM < = to_date('28/05/15', 'dd/mm/yy') - to_date('19/05/15', 'dd/mm/yy') + 1)
SELECT a.dummy_date, COALESCE( b.open, 0) AS OPEN, COALESCE( b.closed, 0) AS closed
FROM arr_table a
LEFT OUTER JOIN table_ b
ON b.tdate = a.dummy_date
ORDER BY a.dummy_date;
输出:
| DUMMY_DATE | OPEN | CLOSED |
|-----------------------|------|--------|
| May, 19 2015 00:00:00 | 1 | 1 |
| May, 20 2015 00:00:00 | 0 | 1 |
| May, 21 2015 00:00:00 | 0 | 0 |
| May, 22 2015 00:00:00 | 0 | 0 |
| May, 23 2015 00:00:00 | 0 | 0 |
| May, 24 2015 00:00:00 | 0 | 0 |
| May, 25 2015 00:00:00 | 0 | 0 |
| May, 26 2015 00:00:00 | 2 | 0 |
| May, 27 2015 00:00:00 | 1 | 0 |
| May, 28 2015 00:00:00 | 2 | 0 |
所以基本上,查询将是:
with arr_table as (
select to_date(<start_date>, 'dd/mm/yy') + level - 1 dummy_date
from dual
connect by ROWNUM < = to_date(<end_date>, 'dd/mm/yy') - to_date(<start_date>, 'dd/mm/yy') + 1)
SELECT a.dummy_date, COALESCE( b.open, 0) AS OPEN, COALESCE( b.closed, 0) AS closed
FROM arr_table a
LEFT OUTER JOIN <your_table> b
ON b.tdate = a.dummy_date
ORDER BY a.dummy_date;