2013-01-08 83 views
-1

EmployeeA甲骨文自连接检索数据

E_no E_name E_Ag_ref E_Type Status   E_Entry_Date 
----------------------------------------------------------------  
1B Mike  12345  B  Continued 08/01/2013 12:24:20 
1S steve  12345  S  Continued 08/01/2013 12:25:20 
2B Radek  1001  B  Continued 08/01/2013 16:24:20 
2S Rafal  1001  S  nContinued 06/01/2014 20:24:20 

查询:

select * 
from 
    Employee E1, 
    Employee E2 
where 
    ((substr(E1.E_no,1,length(E1.E_no)-1) || 'S')=E2.E_no and E2.E_Type='S') 
    and ((TO_CHAR(E1.E_Entry_Date,'YYYYMMDD HH24:MI:SS')) between ((:startDate)||' '|| (:startTime)) and ((:endDate)||' '||(:endTime)) OR ('ALL' between (:startTime) and (:endTime)) ) 
    and ((TO_CHAR(E2.E_Entry_Date,'YYYYMMDD HH24:MI:SS')) between ((:startDate)||' '|| (:startTime)) and ((:endDate)||' '||(:endTime)) OR ('ALL' between (:startTime) and (:endTime)) ) 
    and E2.E_Type='B' and E1.status='Continued' and E2.status='Continued' 

以上低于3个记录查询返回。

1B Mike  12345  B  Continued 08/01/2013 12:24:20 
1S steve  12345  S  Continued 08/01/2013 12:25:20 
2B Radek  1001  B  Continued 08/01/2013 16:24:20 

输入参数:

startDate:06/01/2012 
endDate: 08/01/2013 

startTime: 13:00:00 
endTIme: 21:00:00 

预期结果:

1B Mike  12345  B  Continued 08/01/2013 12:24:20 

请任何人可以建议,如何解决这个问题。

问候, Komaturi

+0

那么逻辑应该是什么?此外,将日期/时间参数转换为日期并与您存储的日期进行比较,而不是将存储的日期转换为字符串以与输入进行比较 –

+0

[踢坏的恶习:使用旧式JOIN](http: //sqlblog.com/blogs/aaron_bertrand/archive/2009/10/08/bad-habits-to-kick-using-old-style-joins.aspx) - 旧式*逗号分隔的表格样式列表*样式已停止使用ANSI - ** 92 ** SQL标准(** 20年前**!)。 ***请***停止使用它 –

回答

0

我想你要做到这一点:

SQL> select e1.* 
    2 from employee e1 
    3   inner join employee e2 
    4     on substr(e1.e_no, 1, length(e1.e_no)-1) || 'S' = e2.e_no 
    5 where e1.E_Type = 'B' 
    6  and e2.E_Type = 'S' 
    7  and e1.status='Continued' 
    8  and e2.status='Continued' 
    9  and ( '' = 'ALL' -- set the left side to ALL if you don't want to compare dates. 
10   or (e1.E_Entry_Date between to_date('06/01/2012 13:00:00', 'dd/mm/yyyy hh24:mi:ss') 
11         and to_date('08/01/2013 21:00:00', 'dd/mm/yyyy hh24:mi:ss') 
12    and e2.E_Entry_Date between to_date('06/01/2012 13:00:00', 'dd/mm/yyyy hh24:mi:ss') 
13          and to_date('08/01/2013 21:00:00', 'dd/mm/yyyy hh24:mi:ss')) 
14  ); 

E_ E_NAME  E_AG_REF E STATUS  E_ENTRY_DATE 
-- ---------- ---------- - ---------- ------------------- 
1B Mike   12345 B Continued 08/01/2013 12:24:20 

原来的SQL不可能是实际运行。因为即使我们粉饰日期为char转换的东西,你有

E2.E_Type='S' 
AND E2.E_Type='B' 

它不能是真实的(这些人不是或运算的话)。你可能意思是E1.e_type = 'B'我猜。