Select all dates with missing dates SQL Server -
i have 3 tables userinfo
, departments
& checkinout
. , following procedure
alter procedure [dbo].[spgetlogs] @datefrom datetime, @dateto datetime, @userid varchar(max) begin declare @query varchar(max) set @query = 'select badgenumber, name, min(checktime) [check time], checktype [check type] userinfo inner join departments dept on userinfo.defaultdeptid = dept.deptid inner join checkinout on userinfo.userid = checkinout.userid checkinout.userid in (' + @userid + ') , checktime between ''' + convert(varchar, ( @datefrom )) + ''' , ''' + convert(varchar, ( @dateto )) + ''' group checkinout.userid, userinfo.badgenumber, userinfo.name, checktype, convert(varchar, checktime, 101) order checkinout.userid' print @query exec (@query) end exec spgetlogs'01/14/2015', '03/31/2015', 1
which results following
1001 james biser 2015-01-14 06:42:47.000 1001 james biser 2015-01-17 06:38:06.000 1001 james biser 2015-01-18 06:42:58.000 1001 james biser 2015-01-19 06:38:00.000 1001 james biser 2015-01-20 06:43:45.000 1001 james biser 2015-01-21 06:42:14.000 1001 james biser 2015-01-22 06:41:43.000 1001 james biser 2015-01-24 07:25:31.000 1001 james biser 2015-01-25 06:39:14.000 1001 james biser 2015-01-26 06:35:48.000 1001 james biser 2015-01-27 06:39:07.000 1001 james biser 2015-01-28 06:49:51.000 1001 james biser 2015-01-29 06:47:28.000 1001 james biser 2015-01-31 07:21:18.000 1001 james biser 2015-02-01 06:33:34.000
i need show employee absent on dates missing here between 14 & 17, 15 , 16 january date missing. need show james biser absent on missing dates.
you should create table if dates, contains row each day you'll ever need (f. ex. 1.1.2000 - 31.12.2099). can this:
select u.badgenumber, u.name, d.[date], c.checktime, c.checktype userinfo u join departments d on u.defaultdeptid = d.deptid cross join dates d outer apply ( select top 1 checktime, checktype checkinout c u.userid = c.userid , c.checktime >= d.[date] , c.checktime < dateadd(day, 1, d.[date]) order c.checktime asc ) c u.userid in (' + @userid + ') , d.[date] >= ''' + convert(varchar, @datefrom, 112 ) + ''' , d.[date] < ''' + convert(varchar, dateadd(day, 1, @dateto), 112) + ''' group u.userid, u.badgenumber, u.name order u.userid
Comments
Post a Comment