2

I have a database of employees and their attendance. I have to create the date range reports of attendance.

Attendance Database table

Database Schema

I am using below query

SELECT a.* FROM attendance a WHERE a.user_id=10 AND (a.date BETWEEN '2017-01-06' AND '2017-01-10')

Result:- Result by My Query

I also want records for all given date range but some dates record is not present in database and i want that dates shows null values to corresponds to that dates as shown in below image.

Final Output I want

Strawberry
  • 33,750
  • 13
  • 40
  • 57
Manoj Kumar
  • 477
  • 2
  • 8
  • 24

1 Answers1

0

Try this. I am not able to run it but the idea is to generate a date range based on this answer.

  1. Use this date range as derived table d.

  2. Do a d left join attendance adding your condition so you will get all the columns for matching data and null for not matching data.

  3. This will give you rest of the data, except employee id. I suggest you can hardcode it in select query.

    select * from 
        (select a.Date 
            from 
            (
                select curdate() - INTERVAL (a.a + (10 * b.a) + (100 * c.a)) DAY as Date
                from (select 0 as a union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) as a
                cross join (select 0 as a union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) as b
                cross join (select 0 as a union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) as c
            ) a
            where a.Date between '2017-01-06' AND '2017-01-10' 
        ) d
    left join 
        attendance a
    on d.date = a.date
    where 
    a.user_id=10
    
Community
  • 1
  • 1
Utsav
  • 7,914
  • 2
  • 17
  • 38
  • i executed in the database this will not work... i have already googled about it and visited tried all the solution that i found but no single one worked for me.. – Manoj Kumar Jan 11 '17 at 09:12
  • Why will this not work? Will u get any error? It would be easier if you used sqlfiddle.com and create sample tables so one can try running the queries. – Utsav Jan 11 '17 at 09:21