TSQL按时间/小时过滤查询

时间:2013-10-18 16:59:08

标签: sql-server tsql datetime getdate datepart

好的,我正在运行visual studio 2008中的查询构建器。我正在尝试按时间过滤查询结果;也就是说,我希望从昨天开始到昨天中午。  昨天我一直在使用GETDATE() - 1,它提取时间戳mm / dd / yyyy hh:mm:ss  但它会拉动当前时间。为了让它从一天开始运行我附加时间戳来删除时间本身,所以它从一天开始时开始:

convert(varchar(10), getdate()-1, 120)

所以我用它来找到范围,我有:     BETWEEN convert(varchar(10),getdate() - 1,120)AND //这是我需要它在中午切断的地方。

我理解日期时间是这里的数据类型,所以我尝试使用日期部分减去小时/分钟/秒,但是datepart()只返回整数并且不会影响时间。

想法?我如何在中午切断这个

6 个答案:

答案 0 :(得分:3)

试试这个:

--Variables
declare @now datetime = getdate(),
        @yesterday datetime

--Yesterday starting datetime
select @yesterday = convert(datetime, convert(date, dateadd(day,-1,@now)))

--Your query to filter between y'day start and y'day noon
--Note that between means inclusive boundary values. (or use >= and <=)
select * from yourTable
where dateCol between @yesteray and dateadd(hour,12,@yesterday)

答案 1 :(得分:1)

between DateAdd(day, -1, cast(getdate() as date)) and DateAdd(hour, -12, cast(getdate() as date))

编辑:正如评论中所提到的,你不能使用带有日期的小时数,你必须将其强制转换回日期时间,因此:

between DateAdd(day, -1, cast(getdate() as date)) and DateAdd(hour, -12, cast(cast(getdate() as date) as datetime))

答案 2 :(得分:1)

SELECT * FROM T WHERE YourDate BETWEEN CAST(GETDATE()-1 As DATE) AND DATEADD(Hour, -12, CAST(CAST(GETDATE() As DATE) As DATETIME) )

请注意,因为BETWEEN将包含下限和上限,因此如果您不希望BETWEEN被占用,则只需将x >= y and y < z替换为yesterday at 12:00 < / p>

答案 3 :(得分:1)

DECLARE
    @Min DATETIME
  , @Max DATETIME

SELECT
    @Min = DATEADD(DAY, -1, CAST(FLOOR(CAST(GETDATE() AS FLOAT)) AS DATETIME))
  , @Max = DATEADD(HOUR, 12, CAST(FLOOR(CAST(GETDATE() AS FLOAT)) AS DATETIME))

SELECT *
FROM <Table> x
WHERE x.[Date] BETWEEN @Min AND @Max

答案 4 :(得分:1)

DECLARE @CurrentDate DATETIME;
SET @CurrentDate = GETDATE();

DECLARE @StartDate DATETIME, @EndDate DATETIME;

SET @StartDate = DATEADD(DAY, DATEDIFF(DAY, 0, @CurrentDate)-1, 0);
SET @EndDate = DATEADD(HOUR, -12, DATEADD(DAY, DATEDIFF(DAY, 0, @CurrentDate), 0));
SELECT @CurrentDate AS [GetDate], @StartDate AS StartDate, @EndDate AS EndDate;

-- Query
SELECT ... FROM ... WHERE DateTimeColumn >= @StartDate AND DateTimeColumn <= @EndDate
-- or
SELECT ... FROM ... WHERE DateTimeColumn BETWEEN @StartDate AND @EndDate

结果(对于SELECT @variables):

GetDate                 StartDate               EndDate
----------------------- ----------------------- -----------------------
2013-10-18 21:33:27.330 2013-10-17 00:00:00.000 2013-10-17 12:00:00.000

答案 5 :(得分:1)

如果您想获得最近30分钟的结果,您需要使用它。您也可以将MINUTE更改为HOUR

--Get now, hour and second included    
DECLARE @NOW DATETIME = GETDATE() 

--Get 30 mins from now
DECLARE @TranDate DATETIME 
SET @TranDate = CONVERT(DATETIME, CONVERT(DATETIME, DATEADD(MINUTE,-30,@NOW))) 

之后,将以下代码添加到where语句

AND TK.TransactionDate >= @TranDate