oracle sql如何选择第一行和最后一行两个选择

时间:2018-09-14 02:28:00

标签: sql oracle

我有两个选择。第一个是

select usuario,fecha from (
select mam.fecha fecha , u.COD_USUARIO usuario
from r_mod_asignar_material mam ,
r_usuarios u
where  mam.cod_usuario = u.cod_usuario
and u.ID_CENTRO_GESTION = '1'
and trunc(mam.FECHA) = to_date('13/09/2018','dd/mm/yyyy')
and mam.ACCION = 'A'

order by mam.fecha asc ) 
where rownum = 1) a

此选择返回fecha和usuario。

现在我有另一个选择,它是相同的,只是更改了位置。

select usuario,fecha from (
select mam.fecha fecha , u.COD_USUARIO usuario
from r_mod_asignar_material mam ,
r_usuarios u
where  mam.cod_usuario = u.cod_usuario
and u.ID_CENTRO_GESTION = '1'
and trunc(mam.FECHA) = to_date('13/09/2018','dd/mm/yyyy')
and mam.ACCION = 'A'

order by mam.fecha desc ) b1
where rownum = 1

) b

我想在usuario相同的第一和第二个选择中返回fecha和usuario。

我尝试内联选择,但是第一次选择返回的用法与第二次选择返回的用法不同

select a.fecha fecha1, a.usuario usuario1 ,b.fecha fecha2,b.usuario usuario2
from (
select usuario,fecha from (
select mam.fecha fecha , u.COD_USUARIO usuario
from r_mod_asignar_material mam ,
r_usuarios u
where  mam.cod_usuario = u.cod_usuario
and u.ID_CENTRO_GESTION = '1'
and trunc(mam.FECHA) = to_date('13/09/2018','dd/mm/yyyy')
and mam.ACCION = 'A'

order by mam.fecha asc ) 
where rownum = 1) a
join
(select usuario,fecha from (
select mam.fecha fecha , u.COD_USUARIO usuario
from r_mod_asignar_material mam ,
r_usuarios u
where  mam.cod_usuario = u.cod_usuario
and u.ID_CENTRO_GESTION = '1'
and trunc(mam.FECHA) = to_date('13/09/2018','dd/mm/yyyy')
and mam.ACCION = 'A'

order by mam.fecha desc ) b1
where rownum = 1

) b
on a.usuario = b.usuario

2 个答案:

答案 0 :(得分:0)

您可以使用Oracle的KEEP FIRST/LAST

select
  min(mam.fecha) as primera_hora,
  min(u.cod_usuario) keep (dense_rank first mam.fecha) as primero_usuario,
  max(mam.fecha) as ultima_hora,
  max(u.cod_usuario) keep (dense_rank last mam.fecha) as ultimo_usuario
from r_mod_asignar_material mam
join r_usuarios u on u.cod_usuario = mam.cod_usuario and u.id_centro_gestion = 1
where trunc(mam.fecha) = date '2018-09-13'
and mam.accion = 'A';

答案 1 :(得分:0)

使用它们之间的联合,这将起作用:

select usuario,fecha from (
select mam.fecha fecha , u.COD_USUARIO usuario
from r_mod_asignar_material mam ,
r_usuarios u
where  mam.cod_usuario = u.cod_usuario
and u.ID_CENTRO_GESTION = '1'
and trunc(mam.FECHA) = to_date('13/09/2018','dd/mm/yyyy')
and mam.ACCION = 'A'
order by mam.fecha asc ) 
where rownum = 1) a
union all
select usuario,fecha from (
select mam.fecha fecha , u.COD_USUARIO usuario
from r_mod_asignar_material mam ,
r_usuarios u
where  mam.cod_usuario = u.cod_usuario
and u.ID_CENTRO_GESTION = '1'
and trunc(mam.FECHA) = to_date('13/09/2018','dd/mm/yyyy')
and mam.ACCION = 'A'

order by mam.fecha desc ) b1
where rownum = 1;
相关问题