我有SQL查询,我想在结果中添加插入空行,这样很容易看到结果.我想在ORDER BY之后插入它.不知道是否可以做到.
这是我的选择声明.
SELECT TableName.CREWACTIONFACTID
,TableName.CREWKEY as CrewKey
,TableName.EVENTKEY as EventID
,TableName.ACTIONSEQUENCE
,case TableName.ACTIONTYPE
when 'DISPATCHED' then '2-Dispatched'
when 'ASSIGNED' then '1-Assigned'
when 'ENROUTE' then '3-Entoute'
when 'ARRIVED' then '4-Arrived'
else 'unknown'
end as Type
,TableName.STARTDATETIME as StartTime
,TableName.ENDDATETIME as EndTIme
,TableName.DURATION as Duration
FROM DatabaseName.TableName TableName
where
To_Date(to_char(TableName.STARTDATETIME, 'DD-MON-YYYY')) >= To_Date('?DATE1::?','MM/DD/YYYY')
AND To_Date(to_char(TableName.ENDDATETIME, 'DD-MON-YYYY')) <= To_Date('?DATE2::?','MM/DD/YYYY')
ORDER BY TableName.EVENTKEY, TableName.STARTDATETIME,TableName.ACTIONSEQUENCE
Run Code Online (Sandbox Code Playgroud)
你可以,就像迈克尔和戈登那样,只是用一个空行union all,但是你需要在它之前得到它order by:
...
and to_date(to_char(t.enddatetime, 'DD-MON-YYYY')) <=
to_date('?DATE2::?','MM/DD/YYYY')
union all
select null, null, null, null, null, null, null, null
from dual
order by eventid, starttime, actionsequence;
Run Code Online (Sandbox Code Playgroud)
...而且你不能使用caseGordon直接使用的那个,order by因为它不是一个选定的值 - 你会得到一个ORA-07185.(请注意,其中的列名是您在其中分配order by的别名select,而不是表中的别名 ;并且您不包括表名/别名;并且不必对null联合部件中的列进行别名,但你可能想要清楚).
但是这依赖于null在任何实际值之后进行排序,这可能并非总是如此(不确定,但可能受到NLS参数的影响),并且不知道真实eventkey是否null仍然存在.因此,在查询的两个部分中引入虚拟列并将其用于排序可能更安全,但通过嵌套查询将其排除在结果之外:
select crewactionfactid, crewkey, eventid, actionsequence, type,
starttime, endtime, duration
from (
select 0 as dummy_order_field,
t.crewactionfactid,
t.crewkey,
t.eventkey as eventid,
t.actionsequence,
case t.actiontype
when 'DISPATCHED' then '2-Dispatched'
when 'ASSIGNED' then '1-Assigned'
when 'ENROUTE' then '3-Enroute'
when 'ARRIVED' then '4-Arrived'
else 'unknown'
end as type,
t.startdatetime as starttime,
t.enddatetime as endtime,
t.duration
from schema_name.table_name t
where to_date(to_char(t.startdatetime, 'DD-MON-YYYY')) >=
to_date('?DATE1::?','MM/DD/YYYY')
and to_date(to_char(t.enddatetime, 'DD-MON-YYYY')) <=
to_date('?DATE2::?','MM/DD/YYYY')
union all
select 1, null, null, null, null, null, null, null, null
from dual
)
order by dummy_order_field, eventid, starttime, action sequence;
Run Code Online (Sandbox Code Playgroud)
日期处理虽然奇怪,特别是to_date(to_char(...))部分.看起来你只是试图丢失时间部分,在这种情况下你可以使用trunk:
where trunc(t.startdatetime) >= to_date('?DATE1::?','MM/DD/YYYY')
and trunc(t.enddatetime) <= to_date('?DATE2::?','MM/DD/YYYY')
Run Code Online (Sandbox Code Playgroud)
但是将任何函数应用于日期列会阻止对其使用任何索引,因此最好不要单独使用它并使变量部分处于正确状态以进行比较:
where t.startdatetime >= to_date('?DATE1::?','MM/DD/YYYY')
and t.enddatetime < to_date('?DATE2::?','MM/DD/YYYY') + 1
Run Code Online (Sandbox Code Playgroud)
在+ 1增加了一天,所以ID DATE2是07/12/2012,过滤器< 2012-07-13 00:00:00,这是一样的<= 2012-07-12 23:59:59.