I wrote the query below, and it returns the data I need. However, I can’t help but think there’s a better way to write it. What I need is to find all the unique rows in Table1 that have prices greater than the price a specified vendor has in the categories to which the vendor belong. (In theory, there is no limit to the number of categories to which a vendor can belong).
- Table1 is a cross-reference table containing
VendorID,Category, andprice - Table2 contains vendor information
- There is a category table that contains the category names.
…
SELECT DISTINCT Table2.name, Table2.city, Table2.state
FROM Table1 INNER JOIN Table2 ON Table1.VendorID = Table2.VendorID
WHERE Table1.Category IN (49,50,45)
AND Table1.price > (SELECT price FROM Table1 WHERE VendorID = 69041 AND Category = 50)
AND Table1.price > (SELECT price FROM Table1 WHERE VendorID = 69041 AND Category = 49)
AND Table1.price > (SELECT price FROM Table1 WHERE VendorID = 69041 AND Category = 45)
You could use a Common Table Expression or a subquery to pull in all the data you need first and then join your tables to that “view”: