如何获得与用户注册到当前日期的日期不同的日期?我有这样的设想:
我在主表中有一些固定值,如[0, 6, 12, 18, 24, 30, 36, 42 .....]
和假设
诸若此类。我不想使用case语句,因为主表中的值不能修复,但是值模式将被修复。表值模式是这样的:两个连续值的共同差异是6,即
if n=0 then
n+1 = (0 + 6) => 6
谢谢
declare @day int;
declare @regdate datetime = '2019-12-09 19:24:19.623';
declare @currentDate datetime = GETDATE();
SET @day = (SELECT DATEDIFF(day, @regdate, @currentDate) % 6 FROM tblMembers WHERE Id = 1)
PRINT @day
发布于 2019-12-14 03:45:54
我认为你在寻找整数除法,而不是模除法。当两个参数都是整数时,这是Server中的默认行为,因此,由于DATEDIFF
返回一个整数,因此应该这样做:
1 + DATEDIFF(day, @regdate, @currentDate) / 6
发布于 2019-12-14 03:58:53
下面是您可以在以下基础上构建解决方案的方法:
declare @masterTable table (id int, col int);
insert into @masterTable values
(1,0) ,
(2,6) ,
(3,12),
(4,18),
(5,24),
(6,30),
(7,36),
(8,42),
(9,48);
-- test data
declare @day int;
declare @regdate datetime = '2019-12-09 19:24:19.623';
declare @currentDate datetime = GETDATE();
select @day = datediff(day, @regdate, @currentDate)
;with cte as (
select id,
col lowerBound,
-- here we need to provide some fallback value for last record
coalesce(lead(col) over (order by id), 1000) upperBound
from @masterTable
)
select id from (values (@day)) [day]([cnt])
join cte on [day].[cnt] between cte.lowerBound and cte.upperBound
https://stackoverflow.com/questions/59334772
复制