Hi
Check out how to post DDL and example data at
http://www.aspfaq.com/etiquette.asp?id=5006 and
example data as insert statements
http://vyaskn.tripod.com/code.htm#inserts CREATE TABLE [Item]
( ItemID int,
ItemSourceID int,
ItemUniversalKey CHAR(10),
Price int )
CREATE TABLE [Source]
( ItemSourceID Int,
Priority int )
INSERT INTO [Item]( ItemID, ItemSourceID, ItemUniversalKey, Price )
values ( 1, 2, '[key_one]', 15 )
INSERT INTO [Item]( ItemID, ItemSourceID, ItemUniversalKey, Price )
values ( 2, 2, '[key_two]', 25 )
INSERT INTO [Item]( ItemID, ItemSourceID, ItemUniversalKey, Price )
values ( 3, 1, '[key_one]', 15 )
INSERT INTO [Source]( ItemSourceID, Priority )
VALUES (1, 1)
INSERT INTO [Source]( ItemSourceID, Priority )
VALUES (2, 2)
SELECT i.ItemID, i.ItemSourceID, i.ItemUniversalKey, i.Price
FROM [Item] i
JOIN [Source] s ON i.ItemSourceID = s.ItemSourceID
WHERE i.Price = ( SELECT MAX(p.price) from [Item] p WHERE p.price < 30 AND
i.ItemSourceID = p.ItemSourceID )
ORDER BY s.priority desc
John
[quoted text, click to view] <scott@spacehug.com> wrote in message
news:1109527892.419243.313190@z14g2000cwz.googlegroups.com...
> Hello, I'm trying to find the most optimal way to perform a tricky
> query. I'm hoping this is some sort of standard problem that has been
> solved before, but I'm not finding anything too useful so far. I have
> a solution that works (using subqueries), but is pretty slow.
>
> Assume I have two tables:
> [Item]
> ItemID int (Primary Key)
> ItemSourceID int
> ItemUniversalKey uniqueidentifier
> Price int
>
> [Source]
> ItemSourceID
> Priority
>
> I'm looking for a set of ItemIDs that match a query to the Price
> (something like Price < 30), with a unique ItemUniversalKey, taking the
> first item with each key according to Source.Priority.
>
> So, given Item rows like this:
> 1 2 [key_one] 15
> 2 2 [key_two] 25
> 3 1 [key_one] 15
>
> and Source rows like this:
> 1 1
> 2 2
>
> I want results like this:
> 2 2 [key_two] 25
> 3 1 [key_one] 15
>
> Row 1 in Item would be eliminated because it shares an ItemUniversalKey
> with row 3, and row 3's Source.Priority is lower than row 1.
>
> Help!?
>