我想知道sql中给定日期范围内的天数和夜晚。谁能帮我?提前谢谢。
答案 0 :(得分:2)
尝试这样的事情:
declare @t table(datefrom datetime, dateto datetime)
insert @t values('2012-01-01 11:30', '2012-01-01 12:30')
insert @t values('2012-01-01 11:30', '2012-01-02 00:30')
insert @t values('2012-01-01 12:30', '2012-01-02 13:00')
insert @t values('2012-01-01 12:30', '2012-01-02 00:30')
insert @t values('2012-01-01 00:00', '2012-01-03 00:00')
select datefrom, dateto,
datediff(day, datefrom - .5,dateadd(minute, -1, dateto)) nights,
datediff(day, datefrom, dateadd(minute, -1, dateto)+.5) days
from @t t
结果:
datefrom dateto nights days
2012-01-01 11:30 2012-01-01 12:30 1 1
2012-01-01 11:30 2012-01-02 00:30 2 1
2012-01-01 12:30 2012-01-02 13:00 1 2
2012-01-01 12:30 2012-01-02 00:30 1 1
2012-01-01 00:00 2012-01-03 00:00 2 2
答案 1 :(得分:0)
您是否尝试过Datediff
夜
select DATEDIFF (d, getdate()-1,getdate())
天
select DATEDIFF (d, getdate()-1,getdate()) - 1
答案 2 :(得分:0)
请参阅AnandPhadke的评论,以下是代码:)
DECLARE @StartDate DATETIME = '2012-01-01'
DECLARE @EndDate DATETIME = '2012-02-01'
SELECT DATEDIFF(DAY, @StartDate, @EndDate) AS [Days], DATEDIFF(DAY, @StartDate, @EndDate) AS [Nights ]