Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
304 views
in Technique[技术] by (71.8m points)

Query SQL Server From Specific Time On Previous Date To Specific Time On Current Date

Sorry for the noob SQL question. I have a table in SQL with a DateTime column. I need to run a script daily to show any lines from 8am yesterday until 8am today. So for example, today I would run:

select *
from Table
Where DateTime > '2020-12-30 08:00:00.000' and DateTime < '2020-12-31 08:00:00.000'

I also know that I could run this, but this will only give me the previous day through the current time:

select *
from Table
Where DateTime >= DATEADD(day,-1, GETDATE()) and DateTime < GETDATE())

But is there a trick to creating the script so I can get 8am yesterday through 8am today without manually editing the script every day?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I would recommend:

select *
from mytable
where 
    datetime >= dateadd(hour, 8, dateadd(day, -1, convert(datetime, convert(date, getdate()))))
    and datetime < dateadd(hour, 8, convert(datetime, convert(date, getdate()))))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...