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).
VendorID
, Category
, and price
...
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":
;WITH MaxPricePerCategory
AS
(
SELECT MAX(Price) AS [Price]
-- You can remove category if you just need the maximum price
, Category
FROM Table1
WHERE VendorID = 69041
AND Table1.Category IN (49,50,45)
GROUP BY Category
)
SELECT DISTINCT Table2.name
, Table2.city
, Table2.state
FROM Table1
JOIN Table2
ON Table1.VendorID = Table2.VendorID
JOIN MaxPricePerCategory MPPC
ON Table1.Category = MPPC.Category
AND Table1.price > MPPC.Price
Maybe just max it?
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 MAX(price) FROM Table1 WHERE VendorID = 69041 AND Category = IN (49,50,45))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.