Sql server 查找最近日期SQL的记录
我有一个带有DateTime列lastUpdated的表dbo.X和一个可能有数百条记录的CodeProduct列CodeProd,其中CodeProd是重复的,因为该表用作股票历史记录 我的存储过程有参数@Date,我想获取最接近该日期的所有CodeProd,例如,如果我有:Sql server 查找最近日期SQL的记录,sql-server,tsql,sql-server-2012,Sql Server,Tsql,Sql Server 2012,我有一个带有DateTime列lastUpdated的表dbo.X和一个可能有数百条记录的CodeProduct列CodeProd,其中CodeProd是重复的,因为该表用作股票历史记录 我的存储过程有参数@Date,我想获取最接近该日期的所有CodeProd,例如,如果我有: +----------+--------------+--------+ | CODEPROD | lastUpdated | STATUS | +----------+--------------+--------+
+----------+--------------+--------+
| 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'
我想得到:
如何找到它?您可以使用apply:
您可以使用TOP1和TIES来获取每个CODEPROD的一行,该行的最近日期应小于提供的日期
试试下面的代码
SELECT TOP(1) WITH TIES *
FROM [YourTableName]
WHERE lastupdated <= @date
ORDER BY Row_number()
OVER (
partition BY [CODEPROD]
ORDER BY lastupdated DESC);
使用group by codeprod,您可以获得最小absdatediffd、@date、LastUpdate。
然后连接到表:
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))
请参见如果CODEPROD有两行或多行最近,会发生什么情况?例如,CODEPROD 13中有值为20190102和20181231的行。是否应返回20190102或20181231的行?两者都有?@Larnu它应该返回记录20181231By nearched您是指最接近日期的较小记录还是最接近日期的较小/较大记录。@SalmanA较小的记录,最接近该日期的最小值。e、 g:如果@Date是20190101,我有20181231和20190102,我想得到20181231
SELECT TOP(1) WITH TIES *
FROM [YourTableName]
WHERE lastupdated <= @date
ORDER BY Row_number()
OVER (
partition BY [CODEPROD]
ORDER BY lastupdated DESC);
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))