Site Sponsored By: SQLDSC - SQL Server Desired State Configuration
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.
Hi,I need to select ONLY those Customers records who made purchases in ALL 3 years(2007, 2008, 2009), in other words, if a customer has bought merchandise every year in the last 3 years, then I would like to list the customer and all the transactions.Table structure is as follows:CustomerID, DatePurchased, ItemID, QtyOrderedThanks in advance for your help.
Lamprey
Master Smack Fu Yak Hacker
4614 Posts
Posted - 2010-04-19 : 17:17:11
Here is one way:
SELECT *FROM Table AS TINNER JOIN ( SELECT CustomerID FROM Table WHERE DatePurchased >= '20070101' AND DatePurchased < '20100101' GROUP BY CustomerID HAVING COUNT(DISTINCT(YEAR(DatePurchased))) = 3 ) AS D ON T.CustomerID = D.CustomerIDWHERE DatePurchased >= '20070101' AND DatePurchased < '20100101'