加入临时表SQL Server

时间:2013-07-11 14:57:20

标签: sql sql-server database sql-server-2008 select

我有一张定价规则表。我正在使用此查询检索每个ProductTypeID的最大折扣,该折扣指示产品的类型:

SELECT MAX(discount) as BiggestDiscount, ProductTypeID FROM dbo.SellingPriceRules
WHERE ProductTypeID is not null
GROUP by ProductTypeID
ORDER BY ProductTypeID

这非常有效,但是我需要对此进行扩展,并且ProductID的列表会检索我的最大折扣。因此,我需要查找每个ProductTypeID所属的ProductID,并检查我的SellPriceRules数据库中此ProductTypeID的最大折扣。

所以,在我的Discounts表中,我有:

ProductID, Margin

在我的Products表中我有:

ProductID, ProductTypeID

为了获得每个产品的ProductTypeID,我有:

select * from Discounts m
INNER JOIN Product p on p.ProductID = m.ProductID
WHERE ProductTypeID is not null

我现在正在努力加入这两个问题。我只是想在折扣表中获得每个产品的最大折扣,并从我的保证金中减去这个。我如何一起加入这两个退休人员?

非常感谢

4 个答案:

答案 0 :(得分:2)

你的所有逻辑都是正确的。您只需要将一个查询嵌入另一个查询的语法。

SELECT
  p.ProductID,
  p.ProductTypeID,
  m.Margin,
  d.BiggestDiscount,
  m.Margin - d.BiggestDiscount AS AdjustedMargin
FROM Product p
INNER JOIN Discounts m ON (p.ProductID = d.ProductID)
INNER JOIN (
  SELECT
    ProductTypeID,
    MAX(discount) as BiggestDiscount
  FROM SellingPriceRules
  GROUP BY ProductTypeID
) d ON (p.ProductTypeID = d.ProductTypeID)
WHERE p.ProductID IS NOT NULL

答案 1 :(得分:0)

使用相关子查询

SELECT m.ProductID, m.Margin, p.ProductTypeID, 
  m.Margin - (SELECT MAX(discount) 
              FROM dbo.SellingPriceRules 
              WHERE ProductTypeID = p.ProductTypeID)
FROM Discounts m INNER JOIN Product p on p.ProductID = m.ProductID
WHERE p.ProductTypeID IS NOT NULL

特别针对@Annon

的执行计划

enter image description here

答案 2 :(得分:0)

通常,您可以在这种情况下使用CTE。像这样:

;WITH current_discounts (BiggestDiscount, ProductTypeID)
AS (
    SELECT MAX(discount) as BiggestDiscount, ProductTypeID FROM dbo.SellingPriceRules
    WHERE ProductTypeID is not null
    GROUP by ProductTypeID
    ORDER BY ProductTypeID
)

SELECT
    m.ProductID,
    m.Margin - c.BiggestDiscount
FROM Discounts m
INNER JOIN Product p ON p.ProductID = m.ProductID
INNER JOIN current_discounts c ON p.ProductTypeID = c.ProductTypeID

答案 3 :(得分:0)

您可以尝试这样的事情:

select *, Margin-BiggestDiscount from Discounts m
INNER JOIN Product p on p.ProductID = m.ProductID AND p.ProductTypeID is not null
inner join (
SELECT MAX(discount) as BiggestDiscount, ProductTypeID 
FROM dbo.SellingPriceRules
GROUP by ProductTypeID) as r on p.ProductTypeID = r.ProductTypeID