Skip to content
Advertisement

SQL Server: table join based on record-dependent values

There’s a general type of query I’m trying to perform, and I’m not sure how to express it in words so that I can find a discussion of best practices and examples for executing it.

Here’s an example use case.

I have a customers table that has info about customers and an orders table. I want to fetch a subset of records from orders based on customer characteristics, limited by the “earliest” and “latest” dates contained as data in the customers table. It’s essential to the solution that I limit my query results to within this date range, which varies by customer.

CUSTOMERS

ORDERS

A sample use case expressed in words would be: “Give me all Active Orders from Finance customers in New York”.

Desired result is to return the full records from orders table for OrderID‘s 5431,5432,5434.

What is a generally good approach for structuring this kind of query, given an orders table with ~10^6 records?

Advertisement

Answer

You are looking for a join:

For performance in this query, consider the following indexes:

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement