Limiting Query Results

G

Guest

Have two tables. Table1 lists the number of stores per state that I need. Table2 lists all the available stores

I need to Select Distinct T2.StoreID, limiting the number of results to T1.Need where T1.State = T2.State

Example below. Can't figure out the SQL for this. Any ideas

Thanks

Mik

Table1

State Need
------ -----
NY

Table

State StoreID
----- ----------
NY 5
NY 5
NY 5
NY 5
NY 5
 
B

Brian Camire

If there are more stores in a given state than you need, how do you decide
which ones to select? Assuming, you want to select the stores in ascending
order of StoreID, the StoreID in Table2 is unique, and the State in Table1
is unique, you might try a query whose SQL looks something like this:

SELECT
[Table2].*
FROM
[Table2]
INNER JOIN
[Table1]
ON
[Table2].[State] = [Table1].[State]
WHERE
(SELECT
Count(*)
FROM
[Table2] AS [Self]
WHERE
[Self].[State] = [Table2].[State]
AND
[Self].[StoreID] <= [Table2].[StoreID]) <= [Table1].[Need]

Mike Klein said:
Have two tables. Table1 lists the number of stores per state that I need.
Table2 lists all the available stores.
I need to Select Distinct T2.StoreID, limiting the number of results to
T1.Need where T1.State = T2.State.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top