分区以获取正确的日期

时间:2017-08-08 10:20:52

标签: sql sql-server partition-by

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

在以下示例中,我尝试检索正确的FirstScanned Date但未成功:

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

1 个答案:

答案 0 :(得分:1)

你可以使用一个简单的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