在sqlserver中将长时间拆分为月份节 [英] Splitting long span of time into month sections in sqlserver

查看:317
本文介绍了在sqlserver中将长时间拆分为月份节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好



我有两个日期和日期。例如:2013年2月3日到2013年12月10日。我想分开这进入sqlserver 2008中相应的月度部分。我希望输出如下给出从日期到现在

fromdate todate

2/3/2013 31/3/2012

1/4 / 2013 30/4/2013

2013年5月1日2013年5月31日

................. ..........

2013年1月12日10/12/2013



如何做到这一点

在此先感谢

Amrutha

Hi all

I have two dates from date and to date .for eg: 2/3/2013 to 10/12/2013 .i want to split this into corresponding monthly sections in sqlserver 2008 . i want output as below for given fromdate and to date
fromdate todate
2/3/2013 31/3/2012
1/4/2013 30/4/2013
1/5/2013 31/5/2013
...........................
1/12/2013 10/12/2013

how to do this
Thanks in Advance
Amrutha

推荐答案





尝试如下。

Hi,

try like below.
DECLARE @startdt DATETIME, @enddt DATETIME
SELECT @startdt =  '2013-02-03', @enddt =  '2013-12-10'

DECLARE @Sessions TABLE (FromDate DateTime, EndDate DateTime)

WHILE @startdt < @enddt
BEGIN

    if(DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@startdt)+1,0)) > @enddt )
    INSERT INTO @Sessions VALUES (@startdt, @enddt)
    else
    INSERT INTO @Sessions VALUES (@startdt, DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@startdt)+1,0)))
    SET @enddt = DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@startdt)+1,0))
    SET  @startdt = DATEADD(DAY,1,@startdt)
END

SELECT * FROM @Sessions





希望它工作。



hope it works.


大家好

最后我使用了这段代码

hi all
finally i used this code
DECLARE @date1 DATETIME, @date2 DATETIME, @date3 DATETIME, @lastdate DATETIME, @totalMonths INT,@totalDays INT,@counter INT
SET @date1 = '10/22/2011'SET @date2 = '05/25/2012'
SET @totalMonths = DATEDIFF(m, @date1, @date2)
        CREATE TABLE #temp_months
        (start datetime, [end] datetime)
        SET @counter = 0
        SELECT @lastdate= DATEADD( D, -1, DATEADD( mm, DATEDIFF( m, 0, @date1 ) + 1, 0 ) )+1;
        WHILE @counter <@totalMonths
        BEGIN
                SELECT @totalDays=DATEDIFF (d,@date1,@lastdate)
                SELECT @date3=DATEADD(dd,-(DAY(DATEADD(mm,1,@date1))),DATEADD(mm,1,@date1))
                INSERT INTO #temp_months(start,[end]) VALUES (@date1,@date3)
                SET @counter = @counter + 1
                SET @date1=@lastdate
                SET @lastdate = DATEADD(Month, 1, @date1)
         END
       SELECT * FROM #temp_months
drop table #temp_months


这篇关于在sqlserver中将长时间拆分为月份节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆