在两个日期sql之间添加字段

时间:2016-11-01 18:37:23

标签: sql sql-server sql-server-2012

我有按月分割记录的数据,但我想将它们从开始到结束日期折叠成一条连续记录。我有这样做的代码,但是我无法总结那段时间内的付款。

例如:

PAYMENT ID STARTDATE ENDDATE 3800 456 2016-02-21 2016-02-28 1500 456 2016-09-01 2016-09-30 12600 456 2016-10-01 2016-10-31 12200 456 2016-11-01 2016-11-30 3600 456 2016-12-01 2016-12-10

我需要支付2月份的记录才能保持不变,但9月至12月的记录会崩溃为1,我需要将这笔款项汇总为4行。

这是我到目前为止的代码

    SELECT *
    , ROW_NUMBER() OVER (PARTITION BY T.ID ORDER BY T.STARTDATE)       AS [ROW]
    INTO #TEMP2 
    FROM #FINALRECORDS    AS T 

   -- START DATES
   SELECT T.*
   , CASE
   WHEN DATEADD(DAY,-1,T.STARTDATE) = T1.ENDDATE
   THEN 0
   ELSE 1
   END AS [New]
   INTO #NEW
   FROM #TEMP2    AS T
   LEFT JOIN #TEMP2      AS T1  ON T.ID= T1.ID AND T.ROW = T1.ROW +1

   -- END DATES
   SELECT T.*
   , CASE
   WHEN DATEADD(DAY,1,T.ENDDATE) = T1.ENDDATE
   THEN 0
   ELSE 1
   END AS [End]
   INTO #END
   FROM #TEMP2    AS T
   LEFT JOIN #TEMP2      AS T1  ON T.ID= T1.ID AND T.ROW = T1.ROW -1

   -- SINGLE RECORD WITH START AND END DATE
   SELECT *
   FROM (
           SELECT T.*
           , T1.ENDDATE AS [NEW_DISCHAGE]
           , SUM(T.PAYMENT) AS [NEW_PAY]
           , ROW_NUMBER() OVER (PARTITION BY T.ID, T.ROW ORDER BY T1.ENDDATE) AS [ROW2]
           FROM #NEW   AS T
           INNER JOIN #END    AS T1  ON T.ID= T1.ID AND T.ROW <= T1.ROW
           WHERE T.New = 1
           AND T1.[END] = 1

           GROUP BY T.ID, T.STARTDATE, T1.ENDDATE, T.ROW
   ) AS A
   WHERE A.ROW2 = 1

我正在寻找的输出有点像这样:

PAYMENT ID STARTDATE ENDDATE 3800 456 2016-02-21 2016-02-28 29900 456 2016-09-01 2016-09-30

ETA:一个更好的例子

1 个答案:

答案 0 :(得分:1)

您希望按年支付总额吗?

create table #stuff (payment int, id int, startdate date, enddate date)

insert into #stuff values
 (3800,     456,  '2015-02-21','2015-02-28'),
 (1500,    456,  '2016-09-01','2016-09-30'),
 (12600,     456,  '2016-10-01','2016-10-31'),
 (12200,     456,  '2016-11-01','2016-11-30'),
 (3600,      456,  '2016-12-01','2016-12-10')


     select
    sum(payment) as payment,
    id,
    min(startdate) as startdate,
    max(enddate) as enddate
    from #stuff
    group by id, year(enddate)

给这个:

付款ID startdate enddate

3800 456 2015-02-21 2015-02-28

29900 456 2016-09-01 2016-12-10