months between two dates in sql server with starting and end date of each of them in sql server

前端 未结 6 1464
误落风尘
误落风尘 2020-12-20 00:07

i want to get months between two dates with their starting and end dates.Suppose if i enter startdate as \"2017-04-01\" and enddate as \"2017-07-31\", i want list of months

6条回答
  •  长情又很酷
    2020-12-20 00:30

    Here you go...

    created the schema

       create table abc(
          date1 date
        )
    
    //Inserting data into it
        insert into abc values(getdate()), 
        (DATEADD(Month, -1, getdate())),
        (DATEADD(Month, -2, getdate())),
        (DATEADD(Month, -3, getdate())), 
        (DATEADD(Month, -4, getdate()))
    

    and finally the Select Query to fetch the data between Start date and end date:

    select (datename(Month, date1)+' '+convert(varchar(2), date1, 103)) as [Date] from abc 
    where convert(varchar(10), date1, 120) between '2017-05-02' and '2017-07-02'
    

    Another approach to fetch the between two dates data:

    select (datename(Month, date1)+' '+convert(varchar(2), date1, 103)) as [Date] from abc
    where date1 >= (DATEADD(Month, -3, getdate())) AND date1 <=getdate();
    

    And the returned result is:

    this is the Fiddle where you can test this query -> SQL FIDDLE Simple and easy...good luck bro :)

提交回复
热议问题