SQL"分区"检查不正常

时间:2017-06-12 12:29:09

标签: sql sql-server window-functions

我的以下查询工作正常,它根据最新扫描将新产品注册到不同的位置。

我的问题是,有时我会收到ID相同的产品(实际上是可能的)。 在我的波纹管表中有位置,通常当产品达到位置5 时,意味着它已完成,当新产品注册时,它将始终从位置1开始。 正如你在下面看到的,我得到了产品" 2222"再次,我想让我的下面" FirstScanned"检索 2222',1,' 2017-05-17 15:58 而不是 2222',1,' 2017-03-21 09 :50

,min(p.Scanned) over (partition by p.ProductNR) as FirstScanned 

表格:

CREATE TABLE Products
 (
  ProductNR varchar (14),
  Location int,
  Scanned Datetime
  );
 Insert Into Products(ProductNR, Location, Scanned)
 Values('1111', 1, '2017-03-15 09:30'), 
  ('1111', 2, '2017-03-16 11:35'), 
  ('1111', 3, '2017-03-21 12:37'), 
  ('2222', 1, '2017-03-21 09:50'),
  ('2222', 5, '2017-03-21 12:58');
  ('2222', 1, '2017-05-17 15:58');

和查询

select p.ProductNR, p.Location, p.Scanned
    ,case
        when p.FirstScanned >= dateadd(day, -5, getdate()) then 'Less than 5 days old'
        when p.FirstScanned <= dateadd(day, -5, getdate()) then 'More than 5 days old'
        else '0'
     end as Age
from
(
    select p.ProductNR
        ,p.Location
        ,p.Scanned
        ,min(p.Scanned) over (partition by p.ProductNR) as FirstScanned
        ,max(p.Scanned) over (partition by p.ProductNR) as LastScanned
    from Products p
) p
where p.LastScanned = p.Scanned

1 个答案:

答案 0 :(得分:0)

; WITH p1 AS (
    SELECT p.ProductNR
        ,p.Location
        ,p.Scanned
    FROM #Products p
    WHERE p.Location <> 5
)  
, p2 AS (
    SELECT p2.ProductNR
        ,p2.Location
        ,p2.Scanned
        ,min(p2.Scanned) OVER (PARTITION BY p2.ProductNR) AS FirstScanned
        ,max(p2.Scanned) OVER (PARTITION BY p2.ProductNR) AS LastScanned
    FROM p1 p2
)  

SELECT p3.ProductNR
    , p3.Location
    , p3.Scanned
    , CASE 
        WHEN p3.FirstScanned >= dateadd(day, -5, getdate()) THEN 'Less than 5 days old'
        WHEN p3.FirstScanned <= dateadd(day, -5, getdate()) THEN 'More than 5 days old'
        ELSE '0'
     END AS Age
FROM p2 p3
WHERE p3.LastScanned = p3.Scanned