Java
Java

Reputation: 2489

Datediff in date format

I have 2 tables with structure as

Emp Table

id    name

001   Smith
002   Jerry


Leave
sr.no   reason      from_date       to_date      request_by   status 
 1      PL          2011-12-11     2011-12-15      001        Declined

 2      PL          2011-11-13     2011-11-13      001        Approved  

 3      PL          2011-10-02     2011-10-05      002        Declined

Now I have written this query

select DATEDIFF(Leave.from_date,Leave.to_date)as cdate,
Emp.id as emp
from Leave left join Emp 
on Leave.request_by=Emp.id

gives me difference between these 2 dates like...

cdate   emp 
 -4     001  
  0     001
 -3     002

The first thing about this output difference between '2011-12-11 & 2011-12-15 ' need to be 5 as for 5 consecutive days employee is absent. That we achieve it.

But I need this cdate in date format like('%Y%m%d') and + if date difference is say -4 then 4 records should be displayed for that. So I want to write a query which gives output like this......

cdate            emp
2011-12-11       001
2011-12-12       001 
2011-12-13       001
2011-12-14       001
2011-12-15       001
2011-11-13       001
2011-10-02       002
2011-10-03       002
2011-10-04       002
2011-10-05       002

So can anybody tell me what how should I need to write my query to get this output?

Upvotes: 1

Views: 1488

Answers (1)

Devart
Devart

Reputation: 121922

Try this query -

CREATE TABLE temp_days(d INT(11));
INSERT INTO temp_days VALUES
  (0),(1),(2),(3),(4),(5),
  (6),(7),(8),(9),(10),
  (11),(12),(13),(14),(15); -- maximum day difference, add more days here

SELECT l.from_date + INTERVAL td.d DAY cdate, e.id emp
FROM
  `leave` l
LEFT JOIN Emp e
  ON l.request_by = e.id
JOIN temp_days td
  ON DATEDIFF(l.to_date, l.from_date) >= td.d
ORDER BY
  e.id

Upvotes: 2

Related Questions