分区以获得正确的日期

Partition by to get the correct date

我想检索 FirstScanned 列下最早的日期。我的问题是产品可以在某个时候再次注册为新产品,发生这种情况时,我希望 FirstScanned 根据最新扫描检索最早的扫描日期在 地点 1

在以下示例中,我试图检索正确的 FirstScanned 日期但没有成功:

CREATE TABLE [dbo].[Products123](
[ID] [int] NOT NULL,
[GTIN] [varchar](50) NULL,
[LocationID] [int] NULL,
[UserID] [int] NULL,
[Created] [datetime] )

insert into Products123(ID, GTIN, LocationID, UserID, Created) 
Values(1, '12345678910', 1, 3, '2017-06-30 14:58:07.693'), -- Location "1" is when products was registered/scanned for this first time
      (2, '12345678910', 5, 3, '2017-06-30 15:25:12.287'), -- The product is scanned into a new location
      (3, '12345678910', 17, 3, '2017-06-30 14:58:07.693'), -- The product is now scanned into the "end" location and is considered to be closed
      (4, '12345678910', 1, 7, '2017-08-01 11:34:16.347'), -- A month later the same productID has been registered,
      (5, '12345678910', 4, 7, '2017-08-01 11:36:16.460') -- etc


   DECLARE @Prev8workingdays date = CASE
        WHEN datepart(dw, getdate()) IN (2,3,4) THEN dateadd(day,-14, getdate()) 
        WHEN datepart(dw, getdate()) IN (1) THEN dateadd(day,-13, getdate()) 
        ELSE dateadd(day,-12, getdate())
   END
   DECLARE @Pre6WorkingDay date = CASE
        WHEN datepart(dw, getdate()) IN (2) THEN dateadd(day,-9, getdate()) 
        WHEN datepart(dw, getdate()) IN (1) THEN dateadd(day,-8, getdate()) 
        ELSE dateadd(day,-7, getdate())
   END

  select p.GTIN, p.FirstScanned as FirstScan, p.Created As lastScan
from
(
    select p.GTIN
        ,p.LocationID
        ,p.Created
        ,min(p.Created) over (partition by p.GTIN) as FirstScanned
        ,max(p.Created) over (partition by p.GTIN) as LastScanned
    from Products123 p
) p
where p.LastScanned = p.Created and LocationID not in (15,16,17) AND  p.FirstScanned < @Prev8workingdays
Order by FirstScanned

我的结果是这样的:

   GTIN        |       FirstScanned      |   LastScanned       
   12345678910 | 2017-06-30 14:58:07.693 |2017-08-01 11:36:16.460

但应该是:

   GTIN        |       FirstScanned      |   LastScanned       
   12345678910 | 2017-08-01 11:34:16.347 |2017-08-01 11:36:16.460

您只需使用一个简单的 case 语句即可到达那里。取位置 1 的最大日期,这将是最晚的日期

  select p.GTIN, p.FirstScanned as FirstScan, p.Created As lastScan
from
(
    select p.GTIN
        ,p.LocationID
        ,p.Created
        ,max(case when p.LocationID=1 then p.Created else null end) over (partition by p.GTIN) as FirstScanned
        ,max(p.Created) over (partition by p.GTIN) as LastScanned
    from Products123 p
) p
where p.LastScanned = p.Created and LocationID not in (15,16,17) AND  p.FirstScanned < @Prev8workingdays