从字符串中选择日期范围

时间:2012-03-12 16:49:11

标签: sql tsql

我刚刚继承了一个数据库,他将所有日期作为字符串插入 数据看起来像这样

19730815 ...... no further comment on that!

我需要选择3月份出生的人,年龄范围为5-15岁。 请帮我这个t-sql查询谢谢

select * from A1 where DBate = ?????

6 个答案:

答案 0 :(得分:1)

试试这个

select * from A1 where month(convert(datetime, DBate))=3 and (year(getdate)-year(convert(datetime, '20161023'))) between 5 and 15

答案 1 :(得分:1)

您可以使用sql中的SUBSTRING函数从字符串中删除月份和日期,然后进行比较以查找出生年龄和月份。

答案 2 :(得分:0)

好吧,您可以执行一些字符串操作来创建可用的DateTime,然后可以使用它来对当前日期执行DateDiff,并使用Between子句过滤到这些DateDiff的范围。也许是这样的:

select * 
from A1 
where DBate = DateDiff(yy, 
      Convert(datetime, SUBSTRING(BDate,0,4) + "-" + SUBSTRING(BDate,4,2) + "-" + SUBSTRING(BDate,6,2)), 
   GetDate()) 
   BETWEEN 5 AND 15

答案 3 :(得分:0)

由于它是一个int,你可以通过\和%运算符获得一些乐趣来返回年份和月份:

SELECT *
FROM A1
WHERE
    (DBate/100)%100 = 3
AND
    (YEAR(GETDATE()) - (DBate/10000)) BETWEEN 5 AND 15

答案 4 :(得分:0)

datediff()和datepart()的组合。这个例子在计算多年的年龄时会仔细考虑确切的日期。

declare @today datetime; set @today=getdate(); --or declare @today date if SQL 2008+

-- Build some sample data
declare @bds table(id int identity(1,1),bd varchar(8));

insert into @bds values ('19730815') --out of range
, ('20070310') --in range when @today is on or after 3/10/2012
, ('20070315') --out of range when @today is before 3/15/2012
, ('20070801') --out of range
, ('20040305') --in range when @today is on or after 3/05/2012

-- Find ages 5 to 15, born in March
select *
, age=DATEDIFF(yyyy,bd,@today)
    -Case when DATEADD(yyyy,-DATEDIFF(yyyy,bd,@today),@today)>bd then 0 else 1 end
from @bds
where DATEDIFF(yyyy,bd,@today)
    -Case when DATEADD(yyyy,-DATEDIFF(yyyy,bd,@today),@today)>bd then 0 else 1 end
between 5 and 15
and datepart(mm,bd)=3 -- or month(d) in SQL 2008+

结果,@ today = 3/12/2012:

id          bd       age
----------- -------- -----------
2           20070310 5
5           20040305 8

答案 5 :(得分:0)

SELECT *
FROM Contacts
WHERE dbo.AgeInYears(dbo.DateFromDigits(DateOfBirth)) BETWEEN 5 AND 15
AND MONTH(dbo.DateFromDigits(DateOfBirth)) = 3

此处定义了DateFromDigitsAgeInYears函数:

CREATE FUNCTION DateFromDigits(@digits int) RETURNS smalldatetime AS
BEGIN
    RETURN
        CASE WHEN ISDATE(CAST(@digits AS char(8))) = 1
            THEN CAST(CAST(@digits AS char(8)) AS smalldatetime)
        END
END

CREATE FUNCTION AgeInYears(@date smalldatetime) RETURNS int AS
BEGIN
    RETURN
        (SELECT DATEDIFF(YY, @date, GETDATE()) -
            CASE WHEN (MONTH(@date) = MONTH(GETDATE())
                    AND DAY(@date) > DAY(GETDATE()))
                    OR MONTH(@date) > MONTH(GETDATE())
                THEN 1 ELSE 0
            END)
END