2011-11-03 68 views
2

我想爲所有產品獲得最便宜的產品變體。對於一種產品來說,這很容易,但是我無法繞過所有這些產品,而且我也不想使用光標。將查詢轉換爲查看或表值功能

select top 1 
    pv.VariantID 
from 
    ProductVariant pv 
    inner join (select min(price) as Price from productvariant where ProductID = @ProductID) pr 
     on pv.Price = pr.Price 
where 
    pv.ProductID = @ProductID 

這適用於2代表具有以下結構:

Product - ProductID 
ProductVariant - ProductID, VariantID, Price 

我知道你可以做到這一點,沒有人知道如何?

將上述查詢轉換爲標量函數並使用它的最佳方法是?因此,這將成爲:

select 
    ProductID 
    , dbo.NewFunction(ProductID) 
from 
    Product 

回答

3
SELECT ProductID, MIN(Price) MinPrice 
FROM Product JOIN ProductVariant ON Product.ProductID = ProductVariant.ProductID 
GROUP BY ProductID 

,讓你的最低價格。如果你想要使用它的VariantID,那麼你需要再次加入 - 但每個VariantID的價格是唯一的價格?

SELECT VariantID, ProductID, MinPrice 
FROM ProductVariant JOIN 
    (SELECT ProductID, MIN(Price) MinPrice 
    FROM Product JOIN ProductVariant ON Product.ProductID = ProductVariant.ProductID 
    GROUP BY ProductID) min_price 
    ON ProductVariant.ProductID = min_price.ProductID AND ProductVariant.Price = min_price.MinPrice 

如果價格不是每種款式獨特,這將無法正常工作 - 特別是你會得到重複。如果出現這種情況,你可以將其更改爲:

SELECT MIN(VariantID) SmallestVariantID, ProductID, MinPrice 
FROM ProductVariant JOIN 
    (SELECT ProductID, MIN(Price) MinPrice 
    FROM Product JOIN ProductVariant ON Product.ProductID = ProductVariant.ProductID 
    GROUP BY ProductID) min_price 
    ON ProductVariant.ProductID = min_price.ProductID AND ProductVariant.Price = min_price.MinPrice 
GROUP BY ProductID, MinPrice 

這會挑最小的變形標識出重複的。

1

是這樣的嗎?

select pv.VariantID 
from ProductVariant pv1 
join (select min(pv2.price) as Price from productvariant pv2 where pv2.ProductID = pv.ProductID) pr 
     on pv1.Price = pr.Price 
2
select 
    pv.ProductID 
    , min(pv.VariantID) 
from 
    ProductVariant pv 
    inner join (select min(price) as Price, ProductID from productvariant group by ProductID) pr 
     on pv.ProductID = pr.ProductID 
     and pr.Price = pv.Price 
group by 
    pv.ProductID 

這是我已經找到了簡單的解決方案。

0

如果我理解正確,您有多個產品,每個產品都有自己的變體,每個變體都有自己的價格。

如果是這樣的話,我覺得

select p.ProductID, min(pv.Price) 
from Product 
    inner join ProductVariant pv on p.ProductID = pv.ProductID 

將提供結果的最簡單的查詢。