查找最有效数据的 SQL 查询

标签 sql tsql sql-server-2012

我想编写查询以查找最有效的行。我有这些表:

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

还有 sqlfiddle http://sqlfiddle.com/#!6/fe5b1/1/0

我的意图是为库存找到最佳卖家。

如果客户需要30A、20A和42B产品。我需要回到“Mark”和“Peter”,因为 Mark 有两个产品(30A 和 20A),所以不需要 Julia。

我怎样才能在 sql 中解决这个问题?

最佳答案

让它在临时表的帮助下工作

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;

更新:

请尝试使用静态表:
CREATE TABLE tmptable (SellerId int, ProductList nvarchar(max), numberOfProducts int);

tmpTable2 也一样。然后把上面的代码改成
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;

关于查找最有效数据的 SQL 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14870222/

相关文章:

sql-server - INSERT 语句运行正确但抛出 'violation of PK contstraint' 错误?

mysql - SQL 将 int 转换为日期时间

sql - Microsoft Access-案例查询

mysql - SQL查找连续的季度

sql - 在 SQL 中构造 FROM

database - SQL Server 2012 TDE 恢复证书问题

SQL 顺序分组和序列间隙的字符串

mysql - sp_start_job 和 sp_cdc_start_job 有什么区别?

php - 需要 mysql 中多表查询的帮助

mysql - 如何通过聚合另一个表中另一列的数据来创建派生列