我尝试了以下方法,以从SQL结果集中获取两者之间的日期差。我查了一下Google,但没有运气,所以我在下面创建了脚本来完成同样的工作。希望对您有所帮助。
--- Query to get date difference between two rows
declare @table table (olddate datetime, newdate datetime)
create table #table (olddate datetime, newdate datetime)
DECLARE db_cursor CURSOR FOR
SELECT CONVERT(date,[utl_recycle_date] ) as RecycleDate
FROM XYZ
WHERE account_number = '6900' AND match_status = 'F'
AND [utl_recycle_date] IS NOT NULL
AND [utl_recycle_date] > '11/01/2018'
GROUP BY DATEDIFF(DAY, CONVERT(date,[utl_recycle_date] ), CONVERT(date, GETDATE())),CONVERT(date,[utl_recycle_date] )
ORDER BY 1
DECLARE @RecycleDate datetime
DECLARE @NewDate datetime
OPEN db_cursor
FETCH next FROM db_cursor INTO @RecycleDate
WHILE @@FETCH_STATUS = 0
BEGIN
FETCH next FROM db_cursor INTO @NewDate
insert INTO #table (olddate, newdate) values (cast(@RecycleDate as date), cast(@NewDate as date))
set @RecycleDate = @NewDate
END
CLOSE db_cursor
DEALLOCATE db_cursor
select
olddate, newdate,
CASE
WHEN DATEDIFF(DAY, olddate, newdate) = 0 THEN 1
WHEN DATEDIFF(DAY, olddate, newdate) > 0 THEN DATEDIFF(DAY, olddate, newdate)
END AS RecyclerFrequency
FROM #table
drop table #table
答案 0 :(得分:0)
--- Query to get date difference between two rows
declare @table table (olddate datetime, newdate datetime)
create table #table (olddate datetime, newdate datetime)
DECLARE db_cursor CURSOR FOR
SELECT CONVERT(date,[utl_recycle_date] ) as RecycleDate
FROM XYZ
WHERE account_number = '6900' AND match_status = 'F'
AND [utl_recycle_date] IS NOT NULL
AND [utl_recycle_date] > '11/01/2018'
GROUP BY DATEDIFF(DAY, CONVERT(date,[utl_recycle_date] ), CONVERT(date, GETDATE())),CONVERT(date,[utl_recycle_date] )
ORDER BY 1
DECLARE @RecycleDate datetime
DECLARE @NewDate datetime
OPEN db_cursor
FETCH next FROM db_cursor INTO @RecycleDate
WHILE @@FETCH_STATUS = 0
BEGIN
FETCH next FROM db_cursor INTO @NewDate
insert INTO #table (olddate, newdate) values (cast(@RecycleDate as date), cast(@NewDate as date))
set @RecycleDate = @NewDate
END
CLOSE db_cursor
DEALLOCATE db_cursor
select
olddate, newdate,
CASE
WHEN DATEDIFF(DAY, olddate, newdate) = 0 THEN 1
WHEN DATEDIFF(DAY, olddate, newdate) > 0 THEN DATEDIFF(DAY, olddate, newdate)
END AS RecyclerFrequency
FROM #table
drop table #table