使用两个条件从日期范围返回信息

时间:2016-06-10 12:35:26

标签: sql tsql between date-range datepart

我是SQL的新手,我正在尝试从特定日期范围中提取数据。在我的情况下,我想要一周前的数据。我试图让上周满13岁的客户,但我的条款不起作用。有什么建议吗?

select distinct [Account Number], [Date of Birth], [Age in Years]
from adhoc.[Patient Demographics] 
where [Age in Years] = 13 and between datepart(dd,getdate()) and datepart(dd,getdate()-7)

列是:

PracName (varchar(95), null)
Patient ID(int, not null)
Account number (varchar(15), null)
Title (varchar(50), null
First Name (Varchar(95), not null)
Middle Name (varchar(95), not null)
Last Name (varchare(95), not null)
Gender (varchar(1), null
Date of Birth(datetime, null)
Age in Years(int, null)
Age in Months (int, null)
Age in Weeks (int, null)
Age in Days (int, null)
Age in UDS (int, null)
Age Group (varchare(7), no null)

2 个答案:

答案 0 :(得分:0)

请提供列字段。我认为你需要使用 OR 而不是 AND

select distinct [Account Number], [Date of Birth], [Age in Years]
from adhoc.[Patient Demographics] 
where [Age in Years] = 13 OR[Age in Years] between datepart(dd,getdate()) and datepart(dd,getdate()-7)

答案 1 :(得分:0)

你可以试试这个:

select distinct [Account Number], [Date of Birth], [Age in Years]
from adhoc.[Patient Demographics] 
where [Age in Years] = 13 and DATEADD(YEAR, 13, [Date of Birth]) between DATEADD(DAY, -7, GETUTCDATE()) AND getdate() 

我首先将13年添加到当前Date of Birth,然后检查结果日期是否在过去7天内。