简体   繁体   中英

How to check absence of data (SQL Server 2008)

Basically this is a reporting system, where user report their activity daily so I want to check for users who don't report their daily activity.

I join 2 tables with this query to check for people who report in a certain date

SELECT DISTINCT Report.InputDate, User.ID, User.Name
FROM User JOIN Report on User.ID = Report.ID 
WHERE Report.InputDate BETWEEN '2014-02-01' AND '2014-02-04'
ORDER BY Report.InputDate

So if someone didn't report at 2014-02-02 the result will be:

2014-02-01 | Guy | 01 |
2014-02-03 | Guy | 01 |

What I'm looking for is how to check for the people that didn't report at the range of date in the query, so the result will be:

2014-02-02 | Guy | 01 |

(And if possible, it will display a row with a date where no one even report, so if no one report at 2014-02-01 the result will be):

2014-02-01 |  |  |

* update

Let's say the columns in table User are: ID, Name

Columns in table Report are: ID, InputDate

And there is another table, ReportDetail that has columns: ID, ActivityType

Try Executing this

SELECT DISTINCT Report.InputDate, User.NIMK, User.NamaLengkap
FROM User JOIN Report on User.ID = Report.ID 
WHERE not (Report.InputDate  between '2014-02-01' AND '2014-02-04')
ORDER BY Report.InputDate 

i think you need list of each date status(present or absence)

Declare @startdate date='2014-02-01' 
Declare @enddate date= '2014-02-04'

;with cte as
(Select @startdate as dt
union all
select DATEADD(day,1,dt) dt from cte a 

where  DATEADD(day,1,dt) <=@enddate )
,cte1 as
(
SELECT DISTINCT Report.InputDate, User.NIMK, User.NamaLengkap
FROM User JOIN Report on User.ID = Report.ID 
WHERE Report.InputDate BETWEEN '2014-02-01' AND '2014-02-04'

)
--select dt from cte --check this one
select  * from cte a left join cte1 b on a.dt=b.InputDate -- correct this yourself

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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