3

我想在sql中找出给定日期范围内的天数和夜数。谁能帮我?提前致谢。

4

3 回答 3

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
于 2012-10-29T11:34:36.660 回答
0

你有没有尝试过Datediff

夜晚

select DATEDIFF (d, getdate()-1,getdate())

select DATEDIFF (d, getdate()-1,getdate()) - 1
于 2012-10-29T10:43:50.687 回答
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 ]
于 2012-10-29T10:44:39.880 回答