sql - show empty records with date that don't have data -
i have sql table, show employees attendances date,time,employee id , key( in or out), as:
id atttime key attdate 123 08:00 in 2015-08-21 123 06:00 pm out 2015-08-21 123 08:00 in 2015-08-22 123 06:00 pm out 2015-08-22 123 08:00 in 2015-08-23 123 06:00 pm out 2015-08-23 123 08:00 in 2015-08-24 123 06:00 pm out 2015-08-24 123 08:00 in 2015-08-25 123 06:00 pm out 2015-08-25 123 08:00 in 2015-08-26 123 06:00 pm out 2015-08-26 123 08:00 in 2015-08-27 123 06:00 pm out 2015-08-27
now want show dates requested if don't have data.. example: if user request report 01-08-2015 30-08-2015
want output below:
id atttime key attdate null null null 2015-08-01 null null null 2015-08-01 null null null 2015-08-02 null null null 2015-08-02 null null null 2015-08-03 null null null 2015-08-03 null null null 2015-08-04 null null null 2015-08-04 . . . . . 123 08:00 in 2015-08-21 123 06:00 pm out 2015-08-21 123 08:00 in 2015-08-22 123 06:00 pm out 2015-08-22 123 08:00 in 2015-08-23 123 06:00 pm out 2015-08-23 123 08:00 in 2015-08-24 123 06:00 pm out 2015-08-24 123 08:00 in 2015-08-25 123 06:00 pm out 2015-08-25 123 08:00 in 2015-08-26 123 06:00 pm out 2015-08-26 123 08:00 in 2015-08-27 123 06:00 pm out 2015-08-27 null null null 2015-08-28 null null null 2015-08-28 null null null 2015-08-29 null null null 2015-08-29 null null null 2015-08-30 null null null 2015-08-30
how make it?
here's solution creates date-range table , right join
missing days:
declare @startdate date = '2015-08-01', @enddate date = '2015-08-30' ;with date (date) ( select @startdate union select dateadd(day, 1, date) date date < @enddate ), keys ( select 'in' [key] union select 'out' [key] ), inoutdates ( select date, [key] date cross join keys ) select e.id, e.atttime, e.[key], d.date attdate employeetable e right join inoutdates d on d.date = e.attdate , e.[key] = d.[key] option (maxrecursion 0)
if want select in
/out
values key
of missing date, can use:
... select e.id, e.atttime, d.[key], d.date attdate ...
here's sqlfiddle demo.
Comments
Post a Comment