SQL Server从总匹配中返回1行

时间:2018-01-05 10:53:06

标签: sql sql-server min having

我做了一个查询,将我们仓库中产品的产品尺寸与我们新库存位置的尺寸相匹配。以下示例输出:

ArticleNr   Location    Packaging   StockAtLocation NewPackaging    Ranking

0012953     A15074E03       MB           235            33            10
0012953     A15074E03       MB           235            E2            11
0012953     A15074E03       MB           235            E3            12
0012953     A15074E03       MB           235            KK            13
0012953     A15074E03       MB           235            C4            14

0066487     A20057A03       KK           12             KK            13
0066487     A20057A03       KK           12             C4            14

示例:产品0012953目前包装在' MB'但在新仓库中,它可以安装在33,E2,E3,KK和C4中。如果它可以适合多个位置,它应该进入排名最低的位置。在这种情况下,它应该去NewPackaging' 33'排名10.

产品0066487应该以13级排在KK。

如何将查询调整为只返回每个ArticleNr排名最低的记录?

期望的输出:

ArticleNr   Location    Packaging   StockAtLocation NewPackaging    Ranking

0012953     A15074E03       MB           235            33            10
0066487     A20057A03       KK           12             KK            13

查询:

SELECT
  t1.ArticleNr,
  t1.Location AS Location,
  t1.StorageMedium AS Packaging,
  t1.StockAtLocation,
  t2.Verpakking AS NewPackaging,
  t2.Ranking
FROM #Info t1,
     #Dimensions t2
WHERE t1.Length < t2.Lengte 
AND t1.Width < t2.Breedte 
AND t1.Height < t2.Hoogte 
AND t1.Volume < t2.MaxVol 
AND (t1.PartWeightGross / 1000) < t2.MaxWeightArt 
AND (t1.Volume * t1.StockAtLocation) < t2.MaxVol 
AND ((t1.PartWeightGross / 1000) * t1.StockAtLocation) < t2.MaxWeightEmb 
Order by ArticleNr asc, Ranking asc

1 个答案:

答案 0 :(得分:2)

在Select中添加一个ROW_NUMBER,并选择Row_number = 1的位置。

;with cte
as
(
SELECT
RN = ROW_NUMBER() OVER(PARTITION BY t1.ArticleNr ORDER BY ArticleNr asc, Ranking asc),
  t1.ArticleNr,
  t1.Location AS Location,
  t1.StorageMedium AS Packaging,
  t1.StockAtLocation,
  t2.Verpakking AS NewPackaging,
  t2.Ranking
FROM #Info t1,
     #Dimensions t2
WHERE t1.Length < t2.Lengte 
AND t1.Width < t2.Breedte 
AND t1.Height < t2.Hoogte 
AND t1.Volume < t2.MaxVol 
AND (t1.PartWeightGross / 1000) < t2.MaxWeightArt 
AND (t1.Volume * t1.StockAtLocation) < t2.MaxVol 
AND ((t1.PartWeightGross / 1000) * t1.StockAtLocation) < t2.MaxWeightEmb 
)
select
    *
    from cte
        where rn = 1