2017-08-08 56 views
1

我想检索下的最早日期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 

回答

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 
+1

谢谢主席先生,我真的试图case语句前面,但没有成功,但你的作品完美 – MishMish