這是應該得到你想要的東西。
--First i just created some test data
if object_id('tempdb..#temp') is not null drop table #temp
select '8/15/1995' as DOB into #temp union all --Note this person is 21
select '8/16/1995' union all --Note this person is 21 TODAY
select '8/17/1995' union all --Note this person is 21 TOMORROW
select '4/11/1996' union all
select '5/15/1997' union all
select '9/7/2001'
--set the years old you want to use here. Create another variable if you need to use ranges
declare @yearsOld int
set @yearsOld = 21
select
convert(date,DOB) as DOB,
--This figures out how old they are by seeing if they have had a birthday
--this year and calculating accordingly. It is what is used in the filter
--I only put it here so you can see the results
CASE
WHEN CONVERT(DATE, CONVERT(VARCHAR(4), YEAR(GetDate()))+ '-'+ CONVERT(VARCHAR(2),MONTH(DOB)) + '-' + CONVERT(VARCHAR(2),DAY(DOB))) <= GETDATE() THEN DATEDIFF(yy,DOB,GETDATE())
ELSE DATEDIFF(yy,DOB,GETDATE()) -1
END AS YearsOld
from #temp
where
--here is your filter. Feel free to change the >= to what ever you want, or combine it to make it a range.
CASE
WHEN CONVERT(DATE, CONVERT(VARCHAR(4), YEAR(GetDate()))+ '-'+ CONVERT(VARCHAR(2),MONTH(DOB)) + '-' + CONVERT(VARCHAR(2),DAY(DOB))) <= GETDATE() THEN DATEDIFF(yy,DOB,GETDATE())
ELSE DATEDIFF(yy,DOB,GETDATE()) -1
END >= @yearsOld
編輯
這是你的方法,該方法沒有考慮到,如果他們今年過了一個生日。我使用一些測試數據。注意出生於1995年8月18日的人。他們把明天21,但使用(DATEDIFF(小時,DOB,GETDATE())/ 8766)> = @yearsOld當它不應該包括他們...
--First i just created some test data
if object_id('tempdb..#temp') is not null drop table #temp
select '8/15/1995' as DOB into #temp union all --Note this person is 21
select '8/16/1995' union all --Note this person is 21 TODAY
select '8/18/1995' union all --Note this person is 21 TOMORROW
select '4/11/1996' union all
select '5/15/1997' union all
select '9/7/2001'
--set the years old you want to use here. Create another variable if you need to use ranges
declare @yearsOld int
set @yearsOld = 21
select
convert(date,DOB) as DOB,
--This figures out how old they are by seeing if they have had a birthday
--this year and calculating accordingly. It is what is used in the filter
--I only put it here so you can see the results
CASE
WHEN CONVERT(DATE, CONVERT(VARCHAR(4), YEAR(GetDate()))+ '-'+ CONVERT(VARCHAR(2),MONTH(DOB)) + '-' + CONVERT(VARCHAR(2),DAY(DOB))) <= GETDATE() THEN DATEDIFF(yy,DOB,GETDATE())
ELSE DATEDIFF(yy,DOB,GETDATE()) -1
END AS YearsOld
from #temp
where
--here is your filter. Feel free to change the >= to what ever you want, or combine it to make it a range.
(DATEDIFF(hour,DOB,GETDATE())/8766) >= @yearsOld
成績
DOB | YearsOld
1995-08-15 | 21
1995-08-16 | 21
1995-08-18 | 20 --this shouldn't be here...
你想找什麼樣的範圍?年齡在###和###之間的人們? – scsimon
即時尋找0-4,5-9,10-17,18+,我認爲我的錯誤是我在面對錯誤的方向在這個例子中......我現在似乎得到了正確的數字。那感覺... – mol
8760是一年中的小時數,8784是閏年。 8766從哪裏來?你的代碼是否會佔閏年? – scsimon