查找最近日期SQL的记录

时间:2019-03-13 12:50:40

标签: sql-server tsql sql-server-2012

我有一个带有dbo.XDateTime的表lastUpdated和一个可能包含数百条记录的代码产品列CodeProd,其中CodeProd被重复,因为该表被用作“库存历史”

“我的存储过程”具有参数@Date,我想使所有CodeProd最接近该日期,例如,如果我有:

+----------+--------------+--------+
| CODEPROD | lastUpdated  | STATUS |
+----------+--------------+--------+
|       10 |   2-1-2019   |   C1   |
|       10 |   1-1-2019   |   C2   |
|       10 |   31-12-2019 |   C1   |
|       11 |   31-12-2018 |   C1   |
|       11 |   30-12-2018 |   C1   |
|       12 |   30-8-2018  |   C3   |
+----------+--------------+--------+

@Date ='1-1-2019'

我想得到:

+----+--------------+------+
| 10 |    1-1-2019  |   C2 |
| 11 |   31-12-2018 |   C1 |
| 12 |   30-8-2018  |   C3 |
+----+--------------+------+

如何找到它?

4 个答案:

答案 0 :(得分:2)

您可以使用TOP(1) WITH TIES来获取每一行CODEPROD的最接近日期的一行,该日期应小于提供的日期。

尝试使用以下代码。

SELECT TOP(1) WITH TIES * 
FROM   [YourTableName] 
WHERE  lastupdated <= @date 
ORDER  BY Row_number() 
            OVER ( 
              partition BY [CODEPROD] 
              ORDER BY lastupdated DESC); 

答案 1 :(得分:0)

您可以使用apply

select distinct t.CODEPROD, t1.lastUpdated, t1.STATUS
from table t cross apply
     ( select top (1) t1.*
       from table t1 
       where t1.CODEPROD = t.CODEPROD and t1.lastUpdated <= @date
       order by t1.lastUpdated desc
     ) t1;

答案 2 :(得分:0)

您可以使用窗口功能:

WITH cte AS (
    SELECT *, ROW_NUMBER() OVER (PARTITION BY codeprod ORDER BY lastupdated DESC) AS rn
    FROM t
    WHERE lastupdated <= @date
)
SELECT *
FROM cte
WHERE rn = 1

答案 3 :(得分:0)

使用group by codeprod,您可以获得最小的abs(datediff(d, @date, lastupdated))
然后加入表格:

declare @date date = '2019-01-01';
select t.* 
from tablename t inner join (
  select codeprod, min(abs(datediff(d, @date, lastupdated))) mindif 
  from tablename 
  group by codeprod
) g on g.codeprod = t.codeprod and g.mindif = abs(datediff(d, @date, t.lastupdated))

请参见demo