使用 SQL 获取所选日期的最后 24 小时
Get last 24 hours from selected date using SQL
我正在尝试 运行 首先进行子查询以获取特定日期,然后我想使用该日期作为起点以获取从该日期算起的最后 24 小时。这是我想 运行 首先作为子查询
的查询
select ID, FullDatetime from myTable
where selectedDate = 0900 and DT = CONVERT(date, getdate())
然后我想使用上述查询的结果生成所选日期的最后 24 小时。请注意所有数据都在同一个 table 中。我想 运行 另一个查询,该查询为我提供从上面的 selectedDate 开始的最后 24 小时。 FullDatetime 的数据类型是日期时间。请帮忙。谢谢
您可以使用子查询两次来获取您用于过滤日期的日期:
SELECT * FROM myTable
WHERE datevalue BETWEEN (SELECT TOP 1 selectedDate FROM myTable WHERE a = b)
AND DATEADD(hh, -24, (SELECT TOP 1 selectedDate FROM myTable WHERE a = b))
select ID, dateadd(hh, -24, FullDatetime) from myTable /* or (dd, -1, ...) */
where selectedDate = 0900 /* did you mean '0900'? */
and DT = CONVERT(date, getdate())
我怀疑您也可以通过直接计算来完全避免查询:
select dateadd(hh, -15, {fn current_date()})
我正在尝试 运行 首先进行子查询以获取特定日期,然后我想使用该日期作为起点以获取从该日期算起的最后 24 小时。这是我想 运行 首先作为子查询
的查询select ID, FullDatetime from myTable
where selectedDate = 0900 and DT = CONVERT(date, getdate())
然后我想使用上述查询的结果生成所选日期的最后 24 小时。请注意所有数据都在同一个 table 中。我想 运行 另一个查询,该查询为我提供从上面的 selectedDate 开始的最后 24 小时。 FullDatetime 的数据类型是日期时间。请帮忙。谢谢
您可以使用子查询两次来获取您用于过滤日期的日期:
SELECT * FROM myTable
WHERE datevalue BETWEEN (SELECT TOP 1 selectedDate FROM myTable WHERE a = b)
AND DATEADD(hh, -24, (SELECT TOP 1 selectedDate FROM myTable WHERE a = b))
select ID, dateadd(hh, -24, FullDatetime) from myTable /* or (dd, -1, ...) */
where selectedDate = 0900 /* did you mean '0900'? */
and DT = CONVERT(date, getdate())
我怀疑您也可以通过直接计算来完全避免查询:
select dateadd(hh, -15, {fn current_date()})