如何将日期分为月份

时间:2012-05-29 09:15:40

标签: sql sql-server sql-server-2000

使用SQL Server 2000

我希望按月保存详细信息

用户输入

ID = 001
Fromdate = 01/01/2012
Todate = 29/03/2012

ID = 002
Fromdate = 01/05/2012
Todate = 19/06/2012

ID = 003
Fromdate = 01/04/2012
Todate = 30/04/2012
.....

从用户条目中,我想将详细信息插入到table1中,条件如fromdate和todate split in到monthwise(mm / yyyy)

预期产出

ID period fromdate todate

001 01/2012 01/01/2012 31/01/2012
001 02/2012 01/02/2012 29/02/2012
001 03/2012 01/03/2012 29/03/2012
002 05/2012 01/05/2012 31/05/2012
002 05/2012 01/06/2012 19/06/2012
003 04/2012 01/04/2012 30/04/2012
....
....

fromdate,todate fomat是dd/mm/yyyy 期间格式为mm/yyyy

如何在sql server中执行此操作。

需要sql查询帮助

2 个答案:

答案 0 :(得分:1)

首先,创建并填充具有以下列的calendar table(至少):

CREATE TABLE dbo.Calendar (
    BaseDate datetime NOT NULL PRIMARY KEY,
    Period char(7) NOT NULL,
    YearNumber int NOT NULL,
    MonthNumber int NOT NULL,
    IsFirstDayOfMonth bit NOT NULL,
    IsLastDayOfMonth bit NOT NULL
)

然后,此查询将返回您需要的一对fromdatetodate所需的数据,但您当然可以将其放入存储过程并按用户输入或任何方式调用一次从您的应用程序执行SQL:

declare @ID char(3), @FromDate datetime, @ToDate datetime

select @ID ='001', @FromDate = '20120107', @ToDate = '20120917'

select
    @ID as 'ID',
    c.Period,
    case when c.IsFirstDayOfMonth = 0x0 then @FromDate else c.BaseDate end as 'FromDate',
    case when @ToDate < c1.BaseDate then @ToDate else c1.BaseDate end as 'ToDate'
from
    dbo.Calendar c
    join dbo.Calendar c1
    on c.YearNumber = c1.YearNumber and c.MonthNumber = c1.MonthNumber
where
    c.BaseDate between @FromDate and @ToDate and
    (c.IsFirstDayOfMonth = 0x1 or c.BaseDate = @FromDate) and
    c1.IsLastDayOfMonth = 0x1

答案 1 :(得分:1)

您可以使用数字表格(have you got one yet?)来生成月份:

SELECT
  ID,
  Period   = RIGHT(CONVERT(varchar(10), MonthStart, 103), 7),
  /*
  alternatively:
  Period = RIGHT('0' + RTRIM(MONTH(MonthStart), 2) + '/' + RTRIM(YEAR(MonthStart)),
  */
  FromDate = CASE WHEN RangeStart > MonthStart THEN RangeStart ELSE MonthStart END,
  ToDate   = CASE WHEN RangeEnd   < MonthEnd   THEN RangeEnd   ELSE MonthEnd   END
FROM (
  SELECT
    ID,
    RangeStart,
    RangeEnd,
    Monthstart,
    MonthEnd = DATEADD(DAY, -1, DATEADD(MONTH, 1, Monthstart))
  FROM (
    SELECT
      ID         = @ID,
      RangeStart = @RangeStart,
      RangeEnd   = @RangeEnd,
      MonthStart = DATEADD(MONTH, DATEDIFF(MONTH, 0, @RangeStart), 0)
    FROM numbers
    WHERE Number BETWEEN 0 AND DATEDIFF(MONTH, @RnageStart, @RangeEnd)
  ) m
) m

作为数字表的临时替代,您可以使用master..spt_values system table,或者更准确地说,使用type = 'P'的特定子集。因此,您只需使用以下子选项替换上面的FROM numbers

FROM (
  SELECT Number
  FROM master..spt_values
  WHERE type = 'P'
) numbers