preso a lavorare con l'aiuto di tabelle temporanee
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:
Si prega di avere una prova con tabelle statiche:
CREATE TABLE tmptable (SellerId int, ProductList nvarchar(max), numberOfProducts int);
stesso per tmpTable2. Quindi cambia il codice sopra a
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;
Quale tipo di RDBMS stai usando, MS SQL Server, MySQL, PostgreSQL ...? Credo che MS SQL Server come SQL Fiddle lo sta usando. Aggiungi il tag necessario. E il collegamento SQL Fiddle che hai aggiunto, meglio modificare la tua domanda e aggiungerla lì, quindi gli altri utenti che guardano la domanda non devono passare attraverso tutti i commenti per essere sicuri di avere tutte le informazioni – Yaroslav
Penso che il problema qui sia Ozan vuole trovare il numero minimo di fornitori in grado di soddisfare un ordine. Probabilmente vorrai ordinare l'elenco dei fornitori per il numero totale di articoli che possono fornire, tuttavia la codifica potrebbe essere complicata. – bendataclear
Penso che il tuo problema sia più complesso di quanto descritto qui. Cosa succede se entrambi i venditori hanno la stessa quantità di prodotti (ma prodotti diversi?) –