我在下面编写了查询,它返回了我需要的数据。但是,我不禁想到有更好的方法来编写它。我需要的是找到Table1
中价格高于指定供应商在供应商所属类别中的价格的所有唯一行。 (理论上,供应商可以归类的类别数量没有限制。)
VendorID
,Category
和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)
答案 0 :(得分:4)
您可以使用公用表表达式或子查询首先获取所需的所有数据,然后将表连接到“视图”:
;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
答案 1 :(得分:4)
也许只是最大化?
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))