sql >> Base de Datos >  >> RDS >> Sqlserver

Comparación de precios con varias tiendas en sql

Hice un intento con esto, aunque no estaba seguro de cómo quería calcular su columna de porcentaje de diferencia, por lo que es posible que desee ver eso más de cerca.

CREATE TABLE #tempProduct
(
    ID INT,
    SellerName VARCHAR(100),
    Total MONEY,
    Availability VARCHAR(100),
    Offer VARCHAR(100),
    Competitors INT
)

INSERT INTO #tempProduct (ID, SellerName, Total, Availability, Offer)
SELECT DISTINCT p.id, pp.SellerName, pp.Price + ISNULL(pp.Shipping,0), pp.Available, pp.Offer
FROM Products p
JOIN Product_Price pp
    ON p.id = pp.ProductId

-- Get Sears competitors
UPDATE tp
SET Competitors = pp.CompetitorCount
FROM #tempProduct tp
JOIN (
        SELECT ProductId, COUNT(sellerName) [CompetitorCount] 
        FROM Product_Price 
        WHERE SellerName <> 'Sears' AND Price + ISNULL(Shipping,0) IS NOT NULL
        GROUP BY ProductId
    ) pp
    ON pp.ProductId = tp.ID
WHERE tp.SellerName = 'Sears'

 SELECT DISTINCT 
    p.id, 
    p.ProductName,
    p.ProductCategory, 
    p.ProductImage, 
    p.ProductUri, 
    stp.Total [SearsTotal], 
    stp.Availability [SearsAvailability], 
    stp.Offer [SearsOffer], 
    stp.Competitors [#Competitors],
    100 - (((ISNULL(etp.Total,0) + ISNULL(atp.Total, 0))/stp.Competitors)/stp.Total) * 100 [DifferencePercentage(Sears & others)], -- Not sure how you want to calculate price difference
    atp.Total, 
    atp.Availability [AmazonTotal], 
    atp.Offer [AmazonOffer], 
    etp.Total [eBayTotal], 
    etp.Availability [eBayAvailability], 
    etp.Offer [eBayOffer]
 FROM Products p
JOIN Product_Price pp
    ON pp.ProductId = p.ID
JOIN #tempProduct stp
    ON stp.ID = p.id
JOIN #tempProduct etp
    ON etp.ID = p.id
JOIN #tempProduct atp
    ON atp.ID = p.id
WHERE stp.SellerName = 'Sears'  
AND etp.SellerName = 'eBay'
AND atp.SellerName = 'Amazon'