Verstanden mit Hilfe von temporären Tabellen
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 zu arbeiten: mit statischen Tabellen
Bitte testen:
CREATE TABLE tmptable (SellerId int, ProductList nvarchar(max), numberOfProducts int);
gleiche gilt für tmpTable2. Dann ändern Sie obigen Code zu
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;
Welche RDBMS verwenden Sie, MS SQL Server, MySQL, PostgreSQL ...? Ich denke MS SQL Server als SQL Fiddle benutzt es. Fügen Sie das benötigte Tag hinzu. Und den SQL Fiddle Link, den Sie hinzugefügt haben, bearbeiten Sie Ihre Frage besser und fügen Sie sie dort hinzu, damit andere Benutzer, die die Frage betrachten, nicht alle Kommentare durchgehen müssen, um sicherzustellen, dass sie alle Informationen haben – Yaroslav
Ich denke, das Problem hier ist Ozan möchte die Mindestanzahl an Lieferanten finden, die eine Bestellung ausführen können. Wahrscheinlich möchten Sie die Liste der Lieferanten nach der Gesamtzahl der Artikel, die sie liefern können, bestellen. Die Codierung könnte jedoch schwierig sein. – bendataclear
Ich denke, dass Ihr Problem komplexer als hier beschrieben ist. Was ist, wenn beide Verkäufer die gleiche Menge an Produkten haben (aber verschiedene Produkte?) –