Click here to Skip to main content
16,004,574 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
My district manager wants a report to show all stores that haven't ordered merchandise from the distribution warehouse in x number of days.

There is just one table with hundreds and of thousands of records.

The table has an OrdCreateDt field. I am thinking I need to query this table where the OrdCreateDt field is <= whatever number of days the district mgr enters.

But, the dist mgr wants to see the store numbers that did not have orders within these same number of days and the details of what the ordered before the x number of days.

I created this query:
select t.storenum, t.storename, t.mercnum, t.ordcreatedt from all_orders t left join (select storenum from all_orders where OrdCreateDt <= dateadd("dd", -days, convert (varchar(10), getdate(),101)) ) t2 on t1.storenum =t2 storenum where OrdCreateDt < dateadd("dd", -days, convert(varchar(10), getdate(),101))


This takes several seconds to run. Is this the most efficient way to do this?

What I have tried:

Msdn search, Google search, stackoverflow website
Posted
Updated 22-Feb-17 15:16pm
Comments
Bryian Tan 22-Feb-17 20:39pm    
hmmm. I'm having tough time imagining the dummy table schema and the data. Maybe you can help provide those information.
Member 10379103 22-Feb-17 20:56pm    
Ok. The table name is all_orders.

The columns are storenum, storename, mercnum, mercqtyordered, ordcreatedt, merordnum.

The dist mgr wants to see info from all_orders table for stores that haven't placed orders in x number of days. So, he may want to see what stores haven't ordered any merchandise in 100 days. And he wants to see the details of those stores that haven't ordered mercy for those days.

Does any of that help?
Peter Leow 22-Feb-17 21:59pm    
This does not make sense
where OrdCreateDt < dateadd("dd", -days, convert(varchar(10), getdate(),101))
Does he really want the info from the very first record available in the database? Is it useful? Instead, ask him for a specific start date.
Member 10379103 22-Feb-17 23:44pm    
The mgr wants to enter a number of days and not a specific date. The "-days" could be -10 or -30 or -365 days.

1 solution

I think the all in 1 table is a conception problem you should address.

I am not an SQL programmer, but I know how databases works.
1) build a temporary table of all shops
2) find the last order for each shop
3) filter unwanted shops
Because of the all in 1 table problem, changes are that it will be highly inefficient.
With a shop table, it would be easy to store the date of last order.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900