I want to write query for find most effective rows. I have these tables:
Sellers
Id Name
1 Mark
2 Julia
3 Peter
Stocks
Id SellerId ProductCode StockCount
1 1 30A 10
2 2 20A 4
3 1 20A 2
4 3 42B 3
And there sqlfiddle http://sqlfiddle.com/#!6/fe5b1/1/0
My Intent find optimum Seller for stock.
If client want 30A, 20A and 42B products. I need return to "Mark" and "Peter" because Mark have both product(30A and 20A), so not need there Julia.
How can i solve this in sql ?
Got it to work with the help of temporary tables
SELECT
s.SellerId,
ProductList = STUFF((
SELECT ',' + ProductCode FROM Stocks
WHERE s.SellerId = Stocks.SellerId
ORDER BY ProductCode FOR XML PATH('')
)
, 1, 1, ''), COUNT(*) AS numberOfProducts
INTO #tmptable
FROM
Stocks s
WHERE
s.ProductCode IN ('30A','20A','42B')
AND s.StockData > 0
GROUP BY s.SellerId;
/*this second temp table is necessary, so we can delete from one of them*/
SELECT * INTO #tmptable2 FROM #tmptable;
DELETE t1 FROM #tmptable t1
WHERE EXISTS (SELECT 1 FROM #tmptable2 t2
WHERE t1.SellerId != t2.SellerId
AND t2.ProductList LIKE '%' + t1.ProductList + '%'
AND t2.numberOfProducts > t1.numberOfProducts)
;
SELECT Name FROM #tmptable t INNER JOIN Sellers ON t.SellerId = Sellers.Id;
UPDATE:
Please have a try with static tables:
CREATE TABLE tmptable (SellerId int, ProductList nvarchar(max), numberOfProducts int);
same for tmpTable2. Then change above code to
INSERT INTO tmpTable
SELECT
s.SellerId,
ProductList = STUFF((
SELECT ',' + ProductCode FROM Stocks
WHERE s.SellerId = Stocks.SellerId
ORDER BY ProductCode FOR XML PATH('')
)
, 1, 1, ''), COUNT(*) AS numberOfProducts
FROM
Stocks s
WHERE
s.ProductCode IN ('30A','20A','42B')
AND s.StockData > 0
GROUP BY s.SellerId;
INSERT INTO tmpTable2 SELECT * FROM tmpTable;
DELETE t1 FROM tmptable t1
WHERE EXISTS (SELECT 1 FROM tmptable2 t2
WHERE t1.SellerId != t2.SellerId
AND t2.ProductList LIKE '%' + t1.ProductList + '%'
AND t2.numberOfProducts > t1.numberOfProducts)
;
SELECT * FROM tmpTable;
DROP TABLE tmpTable, tmpTable2;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With