2014-01-23 41 views
0

我在Oracle中得到这个表(前3行是):SQL查询来生成这个输出

ID    StartTime     EndTime 
AAAAAA  20-Sep-2009 11:08:00  21-Sep-2009 12:08:54 
BBBBBB  20-Sep-2009 02:08:33  21-Sep-2009 12:08:58 
CCCCCC  20-Sep-2009 10:08:34  21-Sep-2009 12:08:38 

我试图“生成”在SELECT查询每个ID触发,所以我必须为StartTime写1,EndTime为0。我在寻找的结果将是:

Timestamp    Trigger_ID  ID 
20-Sep-2009 11:08:00 1   AAAAAA 
20-Sep-2009 02:08:33 1   BBBBBB 
20-Sep-2009 10:08:34 1   CCCCCC 
21-Sep-2009 12:08:54 0   AAAAAA 
21-Sep-2009 12:08:58 0   BBBBBB 
21-Sep-2009 12:08:38 0   CCCCCC 

[为格式问题道歉]

我想我必须做一些事情,如:

SELECT StartTime, '0' as Trigger_ID, ID From MyTable 

SELECT EndTime, '1' as Trigger_ID, ID From MyTable 

卜我现在不如何将这些输出合并到一个输出中。

有人可以帮我看看这个查询吗?

非常感谢提前! :d

+0

你到目前为止尝试过什么?我们不会为您编写代码,但我们可以帮助您调试您的代码。 –

+0

迄今为止,使用我的代码编辑。对不起,我还没有做过...我的代码迄今是有点愚蠢我想:( –

回答

3

一种选择是使用UNION ALL

select starttime timestamp, 1 trigger_id, id 
from yourtable 
union all 
select endtime, 0, id 
from yourtable 
1

如果您正在使用11g和上面:

with tab(ID,StartTime,EndTime) as 
(select 'AAAAAA', '20-Sep-2009 11:08:00', '21-Sep-2009 12:08:54' from dual union all 
select 'BBBBBB', '20-Sep-2009 02:08:33', '21-Sep-2009 12:08:58' from dual union all 
select 'CCCCCC', '20-Sep-2009 10:08:34', '21-Sep-2009 12:08:38' from dual) 
-------------- 
--End of Data 
-------------- 
select timestamp, trigger_id, id 
    from tab 
unpivot (timestamp for trigger_id in (StartTime as '1', EndTime as '0')); 

输出:

|   TIMESTAMP | TRIGGER_ID |  ID | 
|----------------------|------------|--------| 
| 20-Sep-2009 11:08:00 |   1 | AAAAAA | 
| 21-Sep-2009 12:08:54 |   0 | AAAAAA | 
| 20-Sep-2009 02:08:33 |   1 | BBBBBB | 
| 21-Sep-2009 12:08:58 |   0 | BBBBBB | 
| 20-Sep-2009 10:08:34 |   1 | CCCCCC | 
| 21-Sep-2009 12:08:38 |   0 | CCCCCC |