0

目标:我想找到最低的DayInStockNRCummsold > Balance

查询如下

SELECT TOP (100) PERCENT 
       a.MonthNR
     , a.DayNR
     , a.DayInStock
     , a.CummSold
     , a.WarehouseID
     , a.ItemID
     , a.[Group]
     , a.Balance
     , a.CountryNumber
     , a.Country
  FROM dbo.VW_Critical_01_01 AS a 
  JOIN (SELECT MIN(DayInStock) AS DayInStock
             , MIN(CummSold) AS Cummsold
             , Balance
             , ItemID
             , [Group]
          FROM dbo.VW_Critical_01_01
         WHERE CummSold > Balance
         GROUP BY DayInStock, CummSold, Balance, ItemID, [Group]
      ) AS b 
   ON b.DayInStock = a.DayInStock 
  AND b.ItemID = a.ItemID 
  AND b.[Group] = a.[Group]
ORDER BY a.ItemID, a.DayInStock

查询给出了我的结果:

MonthNR DayNR DayInStock CummSold   ItemID   Group  Balance CountryNumber   Country
**2 4   11  2902.492233 100049V3            1   2894    370 Sweden
2   4   11  2902.492233 100049V3            1   2894    280 Norway
2   4   11  2902.492233 100049V3            1   2894    270 Portugal
2   4   11  2902.492233 100049V3            1   2894    460 Finland
2   4   11  2902.492233 100049V3            1   2894    110 Switzerland**

2   5   12  2982.376102 100049V3            1   2894    370 Sweden
2   5   12  2982.376102 100049V3            1   2894    280 Norway
2   5   12  2982.376102 100049V3            1   2894    270 Portugal
2   5   12  2982.376102 100049V3            1   2894    460 Finland
2   5   12  2982.376102 100049V3            1   2894    110 Switzerland

我只想看到标记为BOLD的值

至于那些CummSold > Balance(2902 大于 2894)并且daynumber是最低的 11 而不是 12

我的 SQL Server 知识似乎到此为止。我搜索并尝试了很多东西,也许我只是忽略了一些非常“愚蠢”的东西

任何帮助或建议将不胜感激

4

2 回答 2

1

对于 SQL Server 2005+,您可以尝试使用分析函数:

;WITH CTE AS
(
    SELECT  a.MonthNR,
            a.DayNR,
            a.DayInStock,
            a.CummSold,
            a.WarehouseID,
            a.ItemID,
            a.[Group],
            a.Balance,
            a.CountryNumber,
            a.Country,
            ROW_NUMBER() OVER(PARTITION BY ItemID, [Group], Country
                              ORDER BY DayInStock) RN
    FROM dbo.VW_Critical_01_01 a
    WHERE CummSold > Balance
)
SELECT *
FROM CTE
WHERE RN = 1
于 2013-01-25T15:21:18.760 回答
0

像这样的东西?

select DayNR
     , DayInStock
     , CummSold
     , WarehouseID
     , ItemID
     , [Group]
     , Balance
     , CountryNumber
     , Country
from(SELECT DayInStock 
          , DayNR
          , DayInStock
          , CummSold
          , WarehouseID
          , ItemID
          , [Group]
          , Balance
          , CountryNumber
          , Country
          , min(DayInStock) over (partition by itemID,Group,Country) as minDayInStock
      FROM dbo.VW_Critical_01_01
      WHERE CummSold > Balance
)V
where V.DayInStock = V.minDayInStock
于 2013-01-25T15:59:26.420 回答