计算记录在我的表中存在的天数

时间:2017-03-22 10:22:26

标签: sql-server datetime case

我有一张包含不同产品的表格,可以不断注册到不同的位置。我想知道这个产品自第一次扫描以来的存在时间以及当前位置的位置。

这是一个例子:

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');

预期产出:

-----------------------------------------------------
| ID           | Current Location | Age
-----------------------------------------------------
| 1111         |  3               | > 5 days
| 2222         |  5               | < 5 days
-----------------------------------------------------

我当前的查询

select ProductNR, 
         Location,
         Scanned,
         case When Scanned >= DATEADD(day, -5, GETDATE()) Then 'Less than 5 days old' 
              When scanned <= DATEADD(day, -5, GETDATE()) Then 'More than 5 days old' else '0' end AS Age    
  From Products

我认为这个查询是完全错误的,并且它也显示了每条记录,我花了很多时间试图弄清楚如何正确地写这个。我希望有人可以提供帮助

2 个答案:

答案 0 :(得分:3)

尝试此查询:

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 :(得分:2)

你能试试吗?

SELECT PRODUCTNR, CASE WHEN DATEDIFF(dd,MIN_DATE, SCANNED) > 5 THEN 'More than 5 days old' eLSE 'Less than 5 days old' END AS LAST_SCANN
FROM (
SELECT PRODUCTNR, LOCATION, SCANNED , ROW_NUMBER() OVER(PARTITION BY PRODUCTNR ORDER BY SCANNED DESC) AS RN
    , MIN(SCANNED) OVER(PARTITION BY PRODUCTNR ) AS MIN_DATE
FROM      PRODUCTS
    ) X WHERE RN=1;