SQL Subtract exactly a year

前端 未结 6 1486
独厮守ぢ
独厮守ぢ 2020-12-06 17:24

First I want to thank everyone for helping me, It gave me a lot of ideas on how I should do this and I came up with my own method I just need help putting it into a query

6条回答
  •  佛祖请我去吃肉
    2020-12-06 18:08

    OK... From your response to Joe Stefanelli, I think that part of what you are really trying to do is avoid having to rewrite the query each year. If that is the case, then you can create a numbers table. A simple and fast example would be like this...

     SELECT TOP 3000
            IDENTITY(INT,1,1) as N
       INTO #Numbers
       FROM Master.dbo.SysColumns sc1,
            Master.dbo.SysColumns sc2
    

    Instant table with integers from 1 to 3000.

    This allows you to join or subselect against the #Numbers table for your query. If you want to make a more limited range, then you can make a table with just the years you like (or a table valued function that will make the same table dynamically).

    You could also take it a bit further and implement a table valued function that will return a two column result

    year offset
    2010 0    --Produced from DATEPART(y,GETDATE())
    2009 -1    --loop/set subtract 1
    2008 -2    --repeat until you have enough...
    

    This way, your where clause could read something like

    SELECT *
    FROM yourTable, yourFunction
    WHERE ((DYYYY = CAST(yourFunction.year as VARCHAR) AND (BOOKED <= DATEADD(yy, yourFunction.offset, GETDATE()))
    

    Note that while the tv functions should save you a bit of maintenance programming each year, you may suffer some minor performance hits.

提交回复
热议问题