SQL查询生成此输出

时间:2014-01-23 00:23:23

标签: sql oracle select

我在Oracle中有这个表(前3行):

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写0,为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

2 个答案:

答案 0 :(得分:3)

一种选择是使用UNION ALL

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

答案 1 :(得分: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 |