2013-07-11 50 views
3

我有一个定价规则表。我检索每个ProductTypeID最大的折扣,这表明产品是哪种类型,使用此查询:加入临时表SQL Server

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

这工作完全,但我需要在这个扩大,并为ProductID的List找回我最大的折扣。所以我需要找到ProductTypeIDProductID属于和检查我的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 

我现在正努力将这两个查询结合在一起。我只想获得折扣表中每个产品的最大折扣,并从我的保证金中扣除此折扣。我怎样才能一起加入这两个退休人员?

非常感谢

回答

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 
+0

@Annon你dbo.SellingPriceRules table.http有问题索引扫描操作://sqlfiddle.com/#! 3/4f986/1 –

+0

鉴于您在SellingPriceRules中使用的示例数据,我对您遇到问题并不感到惊讶。 – Anon

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

+0

当您只需要内部连接 – Anon

+0

时,您正在使用相关子查询(重构为外部连接)进行性能优化。首先,检查它! –

+0

http://msdn.microsoft.com/en-us/library/ms187638.aspx – Anon

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