我有小桌子
Create Table TestDates
(
TestDateId int identity (1,1),
RunDateTime DateTime
)
我会在表格中插入一些值
Insert into TestDates
(RunDateTime)
Values
(getdate())
Insert into TestDates
(RunDateTime)
Values
( DATEADD(DAY, -1, GETDATE()))
Insert into TestDates
(RunDateTime)
Values
( DATEADD(DAY, -2, GETDATE()))
Insert into TestDates
(RunDateTime)
Values
( DATEADD(DAY, -3, GETDATE()))
Insert into TestDates
(RunDateTime)
Values
( DATEADD(Hour, -34, GETDATE()))
Insert into TestDates
(RunDateTime)
Values
( DATEADD(Hour, -12, GETDATE()))
我设法执行不同的查询,只给我带来时间
SELECT DISTINCT
DATENAME(hour, RunDateTime) + ':' +
DATENAME(mi, RunDateTime) AS DistinctDate
from TestDates
但我需要指出今天或昨天出现的时间
例如
DistinctDate IsToday IsYesterday
10:33 N Y
20:31 Y N
8:33 N N
请帮忙
答案 0 :(得分:3)
可以使用带有约会的案例陈述。
SELECT DISTINCT
DATENAME(hour, RunDateTime) + ':' +
DATENAME(mi, RunDateTime) AS DistinctDate,
CASE WHEN DATEDIFF(day, RunDateTime, GETDATE()) = 0 THEN 'Y' ELSE 'N' END IsToday,
CASE WHEN DATEDIFF(day, RunDateTime, GETDATE()) = 1 THEN 'Y' ELSE 'N' END IsYesterday
from TestDates
答案 1 :(得分:2)
确定日期是今天还是昨天的一种方法是:
SELECT DISTINCT
DATENAME(hour, RunDateTime) + ':' + DATENAME(mi, RunDateTime) AS DistinctDate,
CASE WHEN DATEPART(day,RunDateTime) = DATEPART(day,GetDate()) THEN 1
ELSE 0 END as IsToday
FROM TestDates
另一种方法是:
SELECT DISTINCT
DATENAME(hour, RunDateTime) + ':' + DATENAME(mi, RunDateTime) AS DistinctDate,
CASE WHEN DATEDIFF(day,RunDateTime,getdate()) = 0 THEN 1
ELSE 0 END as IsToday
FROM TestDates
IsToday列将在今天显示昨天的其他时间。当你只需要在两者之间进行识别时,这就会产生影响。
基于您的示例的最终结果是:
DistinctDate IsToday
10:33 0
20:31 1
8:33 0