2

我在下面编写了查询,它返回了我需要的数据。但是,我不禁想到有更好的方法来编写它。我需要的是Table1在供应商所属的类别中找到价格高于指定供应商价格的所有唯一行。(理论上,供应商可以属于的类别数量没有限制)。

  • 表 1 是一个交叉引用表,包含VendorIDCategoryprice
  • 表 2 包含供应商信息
  • 有一个包含类别名称的类别表。

...

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)
4

2 回答 2

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))
于 2012-08-14T03:58:05.367 回答
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
于 2012-08-14T03:50:18.613 回答