Please start any new threads on our new site at We've got lots of great SQL Server experts to answer whatever question you can come up with.

Our new SQL Server Forums are live! Come on over! We've restricted the ability to create new threads on these forums.

SQL Server Forums
Profile | Active Topics | Members | Search | Forum FAQ
Save Password
Forgot your Password?

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Help- complicated query
 Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

Starting Member

6 Posts

Posted - 10/15/2012 :  09:28:08  Show Profile  Reply with Quote
I have 2 tables:

I need to get "VIP customers"- meaning customers that ordered at least once a month since they registerd (there is a column [subscription_date] on customers)

I cant figure it out :(
any ideas?

Very Important crosS Applying yaK Herder

52326 Posts

Posted - 10/15/2012 :  10:33:15  Show Profile  Reply with Quote
do you've a calendar table to determine the months? also what will be input? will there be a date range passed by user? ie year, quarter etc period that need to be considered in which customer ordered every month

SQL Server MVP

Go to Top of Page

Constraint Violating Yak Guru

Saudi Arabia
264 Posts

Posted - 10/15/2012 :  12:06:17  Show Profile  Reply with Quote
Try something like this:

SELECT C.customer_name, C.subscription_date, COUNT(*) AS orders_count
  FROM Customers AS C
       (SELECT O.customer_id, DATEADD(MONTH, DATEDIFF(MONTH, 0, O.order_date), 0) AS date
          FROM Orders AS O
         GROUP BY O.customer_id, DATEADD(MONTH, DATEDIFF(MONTH, 0, O.order_date), 0)) AS O
       ON O.customer_id = C.customer_id
          AND >= DATEADD(MONTH, DATEDIFF(MONTH, 0, C.subscription_date), 0)
          AND <= GETDATE()
 WHERE C.subscription_date <= GETDATE()
 GROUP BY C.customer_name, C.subscription_date
HAVING COUNT(*) = DATEDIFF(MONTH, C.subscription_date, GETDATE()) + 1;

For us, there is only the trying. The rest is not our business. ~T.S. Eliot

Muhammad Al Pasha
Go to Top of Page
  Previous Topic Topic Next Topic  
 Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.09 seconds. Powered By: Snitz Forums 2000