title: How to loop through SQL table and find rows that match your IF conditions?
body: <p>Here's what I would like to do.  Let's say I have a table of customers (Table X) who have entered an amusement park like Disneyland.  This customer table is extremely detailed, with columns like name, age, race, income level, zip code where they are from and a time stamp of when they entered the park.</p>
  
  <p>For each row in Table X, I would like to query another customer-info table (Table Y) to identify all other customers who share common characteristics with the row in question, and who have entered the Disneyland premises at an earlier point in time.  </p>
  
  <p>For example, from Table X I'm looking at Joe who is a 49 year old guy from Texas who makes $70,000 who visited Disneyland on June 10th, 2013.  While my loop is on Joe's row, I want to search Table Y for all 49 years old males from Texas who also makes $70,000 but visited Disneyland BEFORE Joe.  I'd like to group the Table X row, and the results from Table Y together (bunched together).  What's the best way of doing this in SQL? </p>
  
  <p>If it were VB I know how to do this using a For Next loop with If statements inside.  But the data is in a SQL database, and I want to learn how to do the equivalent.</p>
  
  <p>(Using SQL Server Management Studio)</p>