日期范围之间的每组最小值

时间:2019-09-01 23:05:11

标签: sql-server ssms

我正在尝试根据列的开始和结束信息之间的每个产品ID查找最小值。

原始表格如下:

Supplier_ID          Date            Min Per Day      Flag
------------------------------------------------------------
863703036147077      2019-06-14      0                0
863703036147077      2019-06-15      0                0
863703036147077      2019-06-16      48               1
863703036147077      2019-06-17      47               1
863703036147077      2019-06-18      0                0
863703036147077      2019-06-19      0                0
863703036147077      2019-06-20      0                0
863703036147077      2019-06-21      0                0
863703036197742      2019-06-14      0                0
863703036197742      2019-06-15      4                1
863703036197742      2019-06-16      4                1
863703036197742      2019-06-17      0                0
863703036197742      2019-06-18      0                0
863703036197742      2019-06-19      1                1
863703036197742      2019-06-20      2                1
863703036197742      2019-06-21      0                0

这是我要实现的...将日期分为2列,其中开始和结束以及最后一列为我提供每天的最小值。

Supplier_ID        StartDate     EndDate       Min
---------------------------------------------------
863703036147077    2019-06-16    2019-06-17    47
863703036197742    2019-06-15    2019-06-17    4
863703036197742    2019-06-19    2019-06-21    1

在我写的脚本下面,但我无法进一步进行以获得目标的结果。

SELECT
    Supplier_Id
    , Date
    , [Min Per Day]
    , CASE WHEN Flag = 1 AND [Min Per Day] > 0 THEN MIN( [Min Per Day] ) OVER ( PARTITION BY [Supplier_Id] ORDER BY [Supplier_Id], Date ASC RANGE UNBOUNDED PRECEDING) ELSE NULL END
FROM [Data]

1 个答案:

答案 0 :(得分:0)

也许这可以帮助您

Select a.Supplier_ID, a.StartDate, a.EndDate, b.Min_Per_Day 
From (
  Select Supplier_ID, Max(Date) As StartDate, Min(Date) As EndDate
  From MyTable
  Group By Supplier_ID
) a
Left Join (
  Select Supplier_ID, Min(Min_Per_Day) As Min_Per_Day
  From MyTable
  Group By Supplier_ID
) b On a.Supplier_ID = b.Supplier_ID