使用日期和时间从表中选择全部

时间:2017-07-20 06:11:06

标签: sql sql-server

如何获取昨天和前一天23:59的最后记录数据?

我的代码没有时间过滤器,所以它只显示昨天和前一天的所有数据。

select *
from tbl_Total
where date between  DATEADD(day, -3, GETDATE()) AND DATEADD(day, -1, GETDATE())

4 个答案:

答案 0 :(得分:0)

此查询将返回时间为23:59:59的日期。

SELECT CAST(CAST(CAST(DATEADD(day, -1, GETDATE()) as DATE) as varchar(12)) +' 23:59:59' as datetime2)

因此,您可以在查询中使用它:

select *
from tbl_Total
where date between  DATEADD(day, -3, GETDATE()) AND CAST(CAST(CAST(DATEADD(day, -1, GETDATE()) as DATE) as varchar(12)) +' 23:59:59' as datetime2)

编辑:更优雅的方式:

SELECT DATEADD(second, -1, DATEADD(dd, DATEDIFF(dd,0,GETDATE()),0))

此查询返回昨天的日期,时间为23:59:59。

EDIT2:如果您想在前一天的时间23:59:59返回,则需要使用此查询:

SELECT DATEADD(second, -1, DATEADD(dd, DATEDIFF(dd,1,GETDATE()),0))

如果您想获得任何其他日期,可以更改号码2并进行测试。

答案 1 :(得分:0)

在你的情况下,

select * from tbl_Total as of timestamp timestamp '2017-07-19 23:59:59'

select * from tbl_Total as of timestamp timestamp '2017-07-18 23:59:59'

答案 2 :(得分:0)

试试这个

select *
from tbl_Total
where date between  dateadd(day,-3,convert(varchar(10),getdate(),112)) AND dateadd(day,-3,convert(varchar(10),getdate(),112)+ ' 23:59:59:997' )

答案 3 :(得分:0)

假设您不知道使用ROW_NUMBER获取最新行的确切时间:

with cte as
 ( select *,
      row_number() -- for each day sorted descending
      over (partition by DATEADD(dd, DATEDIFF(dd,0,GETDATE()),0)
      order by date desc) as rn
   from tbl_Total
   where -- yesterday between 23:59 and 23:59:99.999
    (     date >= DATEADD(dd, DATEDIFF(dd,0,GETDATE()),0) - (1.0/1440)
      and date <  DATEADD(dd, DATEDIFF(dd,0,GETDATE()),0)
    )
   or    -- day before yesterday between 23:59 and 23:59:99.999
    (     date >= DATEADD(dd, DATEDIFF(dd,1,GETDATE()),0) - (1.0/1440)
      and date <  DATEADD(dd, DATEDIFF(dd,1,GETDATE()),0)
    )
 )
select * from cte
where rn = 1 --latest row only