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.

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 Returning data NOT there

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 DateOfBusiness
101 01-01-2014
101 01-02-2014
101 01-03-2014
101 01-04-2014
101 01-06-2014
101 01-07-2014

If 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 table

something like

select s.storeid, c.[date]
from store s
cross join calendar c
where 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]

Go to Top of Page

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 DateOfBusiness
101 01-01-2014
101 01-02-2014
101 01-03-2014
101 01-04-2014
101 01-06-2014
101 01-07-2014

If 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 Calendar
AS
(
SELECT MIN(DateOfBusiness) AS Dt
FROM StoreTable
UNION ALL
SELECT DATEADD(dd,1,Start)
FROM Calendar
WHERE DATEADD(dd,1,Start) < = (SELECT MAX(DateOfBusiness) AS STart
FROM StoreTable)
)

SELECT st.StoreID,c.Dt AS MissingDate
FROM Calendar c
CROSS JOIN (SELECT DISTINCT StoreID FROM StoreTable) st
WHERE NOT EXISTS(SELECT 1
FROM StoreTable st1
WHERE st1.StoreID = st.SToreID
AND st1.DateOfBusiness = c.Dt
)
ORDER BY StoreID,MissingDate


------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/
https://www.facebook.com/VmBlogs
Go to Top of Page
   

- Advertisement -