多年来物品的年度总计

时间:2014-10-20 13:47:10

标签: tsql datediff

我想找到每年的总数

例如

  Start date  End Date   Total Value
1 07/01/14    01/01/15   $10,000
2 08/01/13    12/01/14   $10,000
3 03/01/13    05/01/15   $10,000

如您所见,有些项目超过多年。有没有办法找出每年的总价值。

解决方案应该是:

item 3 
2013- $3600 
2014-$4800 
2015-1600 

然后,所有三个项目的总和将减少,以给出年度总数。

到目前为止我所拥有的: 我有一个滚动求和代码,如下所示。

case when 
  (
    [begin date] >= dateadd(mm,0,DATEADD(mm,DATEDIFF(mm,0,getdate()),0)) 
    and [end date] >= dateadd(mm,0,DATEADD(mm,DATEDIFF(mm,0,getdate()),0))
  )
  OR
  (
    [Begin Date] < dateadd(mm,0,DATEADD(mm,DATEDIFF(mm,0,getdate()),0)) 
    and [End Date] >= dateadd(mm,0,DATEADD(mm,DATEDIFF(mm,0,getdate()),0))
  ) 
then [Totalvalue]/nullif(DATEDIFF(mm,[begin date],[end date]),0)
else 0 
end [Current Month]

1 个答案:

答案 0 :(得分:0)

我不知道你如何获得第3项的总价值

但是对于第3项,我希望它应该是

2013 = 3704 
2014 = 4444 
2015 = 1852 

Dono这个代码的效率只是试一试

CREATE TABLE #tblName
  (
     itemid    INT,
     startdate DATETIME,
     endate    DATETIME,
     value     int
  )

INSERT INTO #tblName
VALUES      (1,'2014/07/01','2015/01/01',10000),
            (2,'2013/08/01','2014/12/01',10000),
            (3,'2013/03/01','2015/05/01',10000) 

DECLARE @mindate DATETIME,
        @maxdate DATETIME

SELECT @mindate = Min(startdate),
       @maxdate = Max(endate)
FROM   #tblName

SELECT *
FROM   #tblName;


WITH cte
     AS (SELECT @mindate startdate
         UNION ALL
         SELECT Dateadd(mm, 1, startdate) startdate
         FROM   cte
         WHERE  startdate <= Dateadd(mm, -1, @maxdate))
SELECT a.value * ( ( convert(numeric(22,6),a.cnt) / convert(numeric(22,6),c.total) ) * 100 ) / 100,a.itemid,a.startdate
FROM   (SELECT Avg(value)        value,
               Count(1)          cnt,
               itemid,
               Year(a.startdate) startdate
        FROM   cte a
               JOIN #tblName b
                 ON a.startdate BETWEEN b.startdate AND b.endate
        GROUP  BY itemid,
                  Year(a.startdate)) a
       JOIN(SELECT Sum(cnt) total,
                   itemid
            FROM   (SELECT Avg(value)        value,
                           Count(1)          cnt,
                           itemid,
                           Year(a.startdate) startdate
                    FROM   cte a
                           JOIN #tblName b
                             ON a.startdate BETWEEN b.startdate AND b.endate
                    GROUP  BY itemid,
                              Year(a.startdate)) B
            GROUP  BY itemid) C
         ON a.itemid = c.itemid
WHERE  a.itemid = 3