SQL select * from column where year = 2010

前端 未结 5 2344
别那么骄傲
别那么骄傲 2020-12-15 03:08

This is probably a simple where clause but I want to say, from columnX (which is datetime) I want all rows where just the year = 2010.

so:

select * f         


        
相关标签:
5条回答
  • 2020-12-15 03:52

    If i understand that you want all rows in the year 2010, then:

    select * 
      from mytable 
     where Columnx >= '2010-01-01 00:00:00' 
           and Columnx < '2011-01-01 00:00:00'
    
    0 讨论(0)
  • 2020-12-15 03:57

    T-SQL and others;

    select * from t where year(Columnx) = 2010
    
    0 讨论(0)
  • 2020-12-15 04:08

    its just simple

      select * from myTable where year(columnX) = 2010
    
    0 讨论(0)
  • 2020-12-15 04:12
    select * from mytable where year(Columnx) = 2010
    

    Regarding index usage (answering Simon's comment):

    if you have an index on Columnx, SQLServer WON'T use it if you use the function "year" (or any other function).

    There are two possible solutions for it, one is doing the search by interval like Columnx>='01012010' and Columnx<='31122010' and another one is to create a calculated column with the year(Columnx) expression, index it, and then do the filter on this new column

    0 讨论(0)
  • 2020-12-15 04:14

    NB: Should you want the year to be based on some reference date, the code below calculates the dates for the between statement:

    declare @referenceTime datetime = getutcdate()
    select *
    from myTable
    where SomeDate 
        between dateadd(year, year(@referenceTime) - 1900, '01-01-1900')                        --1st Jan this year (midnight)
        and dateadd(millisecond, -3, dateadd(year, year(@referenceTime) - 1900, '01-01-1901'))  --31st Dec end of this year (just before midnight of the new year)
    

    Similarly, if you're using a year value, swapping year(@referenceDate) for your reference year's value will work

    declare @referenceYear int = 2010
    select *
    from myTable
    where SomeDate 
        between dateadd(year,@referenceYear - 1900, '01-01-1900')                       --1st Jan this year (midnight)
        and dateadd(millisecond, -3, dateadd(year,@referenceYear - 1900, '01-01-1901')) --31st Dec end of this year (just before midnight of the new year)
    
    0 讨论(0)
提交回复
热议问题