我试图实现一个简单的SQL查询,该查询在今天的固定时间(例如18:00)和昨天的固定时间(例如18:00)之间获取记录。
SELECT * FROM [Table]
WHERE [Table].[Date Time] > Now()-1;
但是,这将返回今天当前时间和昨天之间的所有记录。
有没有办法在指定的时间内返回记录?
编辑: 我尝试了这个查询,但它抛出了语法错误。
SELECT * FROM [Table]
WHERE [Date Time] BETWEEN FORMAT(DATEADD(DAY, - 1, NOW()) AS DATETIME) + FORMAT('18:00:00' AS TIME) AND FORMAT(NOW() AS DATETIME) + FORMAT('18:00:00' AS TIME);
任何帮助?
答案 0 :(得分:1)
你的意思是这样的吗?
SELECT *
FROM [Table]
WHERE [Table].[Date Time] between #16/11/2016 14:00:00# and #17/11/2016 14:00:00#
但要注意MDY - DMY日期格式..
我更喜欢ODBC C格式以避免出现问题:
SELECT *
FROM [Table]
WHERE [Table].[Date Time] between {ts'1970-01-12 14:00:00' } and {ts'1975-01-12 14:00:00'}
答案 1 :(得分:1)
您需要添加变量日期值和固定时间值。
日期/时间常数可以是所有不同的本地格式变幻无常。使用public int compareMembers(MyGroup x)
{
int i = 0;
if (this.firstMember == x.firstMember)
{ i++; }
if (this.secondMember == x.secondMember)
{ i++; }
if (this.thirdMember == x.thirdMember)
{ i++; }
if (this.firstMember == x.secondMember || this.secondMember == x.firstMember)
{ i++; }
if (this.firstMember == x.thirdMember || this.thirdMember == x.firstMember )
{ i++; }
if (this.secondMember == x.thirdMember || this.thirdMember == x.secondMember )
{ i++; }
return i;
}
我们可以避免这种情况:
TimeSerial
(第一个建议,使用德国日期格式)
SELECT *
FROM [Table]
WHERE [Table].[Date Time] Between Date()-1 + TimeSerial(18,0,0)
And Date() + TimeSerial(18,0,0)
查询设计器可以自动将其更改为
SELECT *
FROM [Table]
WHERE [Table].[Date Time] Between Date()-1 + #18:00:00# And Date() + #18:00:00#
Between Date()-1 + #12/30/1899 18:00:00# And Date() + #12/30/1899 18:00:00#
在Access中为“Date zero”。
答案 2 :(得分:0)
尝试以下查询
declare
@StartDate DATE = NULL,
@EndDate DATE = NULL
SELECT * FROM [Table]
WHERE
CAST( [Date Time] AS DATE) >= CAST( ISNULL(@StartDate, '') AS DATE)
AND CAST( [Date Time] AS DATE) <= CAST( ISNULL(@EndDate, '') AS DATE)
或简单地将日期放入@StartDate和@EndDate。
答案 3 :(得分:0)
您可能希望首先在18.00声明今天日期的变量,然后将您的日期与之比较,在Access中您可以使用TimeValue()函数:
Dim Time18
Time18 = TimeValue("18:00")
然后你可以比较你的日期和一天的日期:
SELECT * FROM [Table]
WHERE (
(DateValue([Table].[Date Time]) = DateValue(Now() - 1) AND
TimeValue([Table].[Date Time]) >= Time18) OR
(DateValue([Table].[Date Time]) = DateValue(Now() AND
TimeValue([Table].[Date Time]) <= Time18))
答案 4 :(得分:0)
使用date()而不是now()
假设今天是17nov(任何时间),
如果您需要昨天16nov(00:00 - > 23:59)的记录,您必须使用date() - 1作为下限,将date()作为上限
SELECT *
FROM [Table]
WHERE [Table].[Date Time] between date()-1 and date()
如果您需要今天17nov(00:00 - > 23:59)的记录,您必须使用date()作为下限,并使用date()+ 1作为上限
SELECT *
FROM [Table]
WHERE [Table].[Date Time] between date() and date()+1
这是简单的版本,边界有一点问题,正确的过滤器应该是(昨天)
SELECT *
FROM [Table]
WHERE [Table].[Date Time] >= date()-1 [Table].[Date Time] < date()
或者,今天:
SELECT *
FROM [Table]
WHERE [Table].[Date Time] >= date() [Table].[Date Time] < date()+1
答案 5 :(得分:0)
您可以尝试以下SQL Server查询:
SELECT * FROM [Table]
WHERE DATEADD(HH, 18, CAST(CAST([Table].[Date Time] AS DATE) AS DATETIME)) > DATEADD(HH, 18, CAST(CAST(Now() AS DATE) AS DATETIME))-1;