简体   繁体   English

查找日期范围之间的差距SQL Oracle

[英]Find Gap between dates ranges SQL Oracle

l want to get the gap between dates range via SQL query lets see the situation: 我想通过SQL查询来获取日期范围之间的差距,让我们看一下情况:

l have table employees like : Every month the employee deserve payment l有表员工,例如:每个月员工应得的报酬

 ID  Name     From_date    To_date    Paid_Amount`

  1    ali     01/01/2002  31/01/2002    300
  2    ali     01/02/2002  28/02/2002    300
  3    ali     01/04/2002  30/04/2002    300
  4    ali     01/05/2002  31/05/2002    300
  5    ali     01/07/2002  31/07/2002    300

Now, we notice there are no payments in March and June 现在,我们注意到三月和六月没有付款
so, how by SQL query I can't get these months ?? 那么,如何通过SQL查询我这些月不能得到?

Try this, 尝试这个,

with mine(ID,Name,From_date,To_date,Paid_Amount) as
(
 select  1,'ali','01/01/2002','31/01/2002',300 from dual union all
 select  2,'ali','01/02/2002','28/02/2002',300 from dual union all
 select  3,'ali','01/04/2002','30/04/2002',300 from dual union all
 select  4,'ali','01/05/2002','31/05/2002',300 from dual union all
 select  5,'ali','01/07/2002','31/07/2002',300 from dual
 ),
 gtfirst (fromdt,todt) as (
       select min(to_Date(from_Date,'dd/mm/yyyy')) fromdt,max(to_Date(to_Date,'dd/mm/yyyy')) todt from mine
 ),
 dualtbl(first,last,fromdt,todt) as
 (
     select * from(select TRUNC(ADD_MONTHS(fromdt, rownum-1), 'MM') AS first,TRUNC(LAST_DAY(ADD_MONTHS(fromdt, rownum-1))) AS last,fromdt,todt from gtfirst connect by level <=12)
     where first between fromdt and todt and last between fromdt and todt
 )
select to_char(first,'month') no_payment_date from dualtbl where first not in (select to_Date(from_Date,'dd/mm/yyyy') from mine)
and first not in (select to_Date(to_date,'dd/mm/yyyy') from mine)

If you want to get the date difference between one payment date and the previous payment date and the ID field is sequential, then you may simply join back to the table and select the previous row. 如果您想获得一个付款日期与上一个付款日期之间的日期差, 并且 ID字段是连续的,则可以简单地加入表格并选择上一行。

SELECT X.From_date, Y.From_date, Y.From_date - X.From_date Difference
FROM Employees X
LEFT OUTER JOIN Employees Y ON Y.ID = X.ID - 1

If the ID field is not sequential, then you can use a similar method, but build a temporary table with a row index that you can use to join back to the previous payment. 如果ID字段不是连续的,则可以使用类似的方法,但是可以建立一个具有行索引的临时表,您可以使用该表将其联接回先前的付款。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM