2013-07-11 184 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