Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
Author |
Topic |
JAdauto
Posting Yak Master
160 Posts |
Posted - 2014-01-30 : 18:00:00
|
Is it possible to return data NOT there for a calendar date. I have a table that lists StoreID and DateofBusiness. I need to report any stores that do not have a record. I dont even know how to start reporting data NOT there.Examples:StoreID DateOfBusiness101 01-01-2014101 01-02-2014101 01-03-2014101 01-04-2014101 01-06-2014101 01-07-2014If I were to run a query for store 101 for the first 7 days of January, I would want this to return store 101 and 01-05-2014.Is this even possible?Thanks,JAdauto |
|
khtan
In (Som, Ni, Yak)
17689 Posts |
Posted - 2014-01-30 : 21:37:12
|
do you have a calendar table that stores all the dates ?LEFT JOIN that to this store - business date tablesomething likeselect s.storeid, c.[date]from store s cross join calendar cwhere c.[date] between '2014-01-01' and '2014-01-07'and not exists ( select * from this_table x where x.storeid = s.storeid and x.DateOfBusiness = c.[date] ) KH[spoiler]Time is always against us[/spoiler] |
|
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2014-01-31 : 07:37:34
|
quote: Originally posted by JAdauto Is it possible to return data NOT there for a calendar date. I have a table that lists StoreID and DateofBusiness. I need to report any stores that do not have a record. I dont even know how to start reporting data NOT there.Examples:StoreID DateOfBusiness101 01-01-2014101 01-02-2014101 01-03-2014101 01-04-2014101 01-06-2014101 01-07-2014If I were to run a query for store 101 for the first 7 days of January, I would want this to return store 101 and 01-05-2014.Is this even possible?Thanks,JAdauto
In case you dont have calendar table use below;With CalendarAS(SELECT MIN(DateOfBusiness) AS DtFROM StoreTableUNION ALLSELECT DATEADD(dd,1,Start)FROM CalendarWHERE DATEADD(dd,1,Start) < = (SELECT MAX(DateOfBusiness) AS STartFROM StoreTable))SELECT st.StoreID,c.Dt AS MissingDateFROM Calendar cCROSS JOIN (SELECT DISTINCT StoreID FROM StoreTable) stWHERE NOT EXISTS(SELECT 1FROM StoreTable st1WHERE st1.StoreID = st.SToreIDAND st1.DateOfBusiness = c.Dt)ORDER BY StoreID,MissingDate ------------------------------------------------------------------------------------------------------SQL Server MVPhttp://visakhm.blogspot.com/https://www.facebook.com/VmBlogs |
|
|
|
|
|
|
|