用于查找最有效数据的SQL查询

时间:2013-02-14 07:58:07

标签: 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产品。我需要回到“马克”和“彼得”,因为马克有两种产品(30A和20A),所以不需要朱莉娅。

我如何在sql中解决这个问题?

2 个答案:

答案 0 :(得分:3)

在临时表的帮助下使用它

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;

答案 1 :(得分:-2)

我认为这可能就是你要找的东西?

Select name,sum(stockdata) as stockdata from sellers s1 join Stocks s2 on s1.id=s2.sellerid
where ProductCode in ('30A','20A','42B')
group by name
order by sum(stockdata) desc

我希望它有所帮助。

如果你只想要前2名。你写了

Select top 2 name,sum(stockdata) as stockdata from sellers s1 join Stocks s2 on s1.id=s2.sellerid
where ProductCode in ('30A','20A','42B')
group by name
order by sum(stockdata) desc

我认为这就是你要找的东西,因为我怎么看,你想选择两个拥有最高stockdata的人?