Sql Server Select语句,累积列

时间:2014-05-05 14:57:44

标签: sql sql-server select join

我在下面的select语句中使用了gridview数据源。我需要在ProjInstDate上计算累积列,如下所示。但是如果你看到结果,我会在同一天的累计总数上得到重复,这是有道理的。但我无法弄清楚的是如何在ProjInstDate上计算累积量,而是针对不同的JobID进行计算。我不确定select语句在这一点上应该是什么样的"(t1.ProjectedInstDate> = t2.ProjectedInstDate)"。我知道这就是问题,但我不确定如何正确地做我想做的事。

select t1.JobID
     , t1.JobName
     , t1.[JobDescription]
     , t1.JobType
     , Convert(varchar, t1.QuoteDate, 101) AS QuoteDate
     , t1.ProjectedInstDate
     , Convert(decimal(12, 0), t1.QuoteTotal) AS QuoteTotal
     , Convert(decimal(12, 0), t1.Prob) AS Prob
     , t1.Completed
     , t1.ProjectManager
     , Convert(decimal(12, 0), t1.ProjectedIncome) AS ProjectedIncome
     , sum(CASE WHEN t1.Completed != 'y' and t1.Prob != 0 
                then Convert(decimal(12, 0),t2.ProjectedIncome) 
                else null end) As CumulativeProjectedIncome
     , Convert(decimal(12, 1), sum(CASE WHEN t1.Completed != 'y' and t1.Prob != 0 
                                        then (t2.ProjectedIncome/1923) 
                                        else null end)) as DAYSOFWORK
     , (CASE WHEN t1.Completed != 'y'and t1.Prob != 0 
             then Convert(decimal(12, 0), (datediff(day, GetDate(), t1.ProjectedInstDate))) 
             else null end) AS DAYSFROMTODAY 
     , (CASE WHEN t1.Completed != 'y' and t1.Prob != 0 
             then Convert(decimal(12, 1), sum(t2.ProjectedIncome/1923)-datediff(day, GetDate(), t1.ProjectedInstDate)) 
             else null end) as DAYSOFREVASOFTODAY
  from ContractPlan t1 
 inner join 
       ContractPlan t2 
    on (t1.ProjectedInstDate >= t2.ProjectedInstDate) 
 where (t2.Completed = 'n' or t2.Completed = 'N') 
   and (t1.Completed = 'N' or t1.Completed = 'n')
 Group By  
       t1.JobID
     , t1.JobName
     , t1.[JobDescription]
     , t1.JobType
     , t1.QuoteDate
     , t1.ProjectedInstDate
     , t1.QuoteTotal
     , t1.Prob
     , t1.ProjectedIncome
     , t1.Completed
     , t1.ProjectManager 
 Order By 
       t1.ProjectedInstDate




ProjInstDate      | QuoteTotal | Prob |Comp | PM| ProjectedIncome | CumulativeIncome
2014-04-16 00:00:00 300 100 N   NULL    300 300
2014-04-17 00:00:00 6000    100 N   NULL    6000    6300
2014-04-18 00:00:00 300 100 N   NULL    300 6600
2014-05-01 00:00:00 9756    100 N   NULL    9756    63637
2014-05-01 00:00:00 28796   75  N   NULL    21597   63637
2014-05-01 00:00:00 11179   50  N   NULL    5590    63637
2014-05-01 00:00:00 20094   100 N   NULL    20094   63637
2014-05-04 00:00:00 2222    90  N   ben 2000    67637
2014-05-04 00:00:00 2222    90  N   ben 2000    67637
2014-05-05 00:00:00 23698   100 N   daved   23698   98835
2014-05-05 00:00:00 6000    100 N   sdf 6000    98835
2014-05-05 00:00:00 1500    100 N   NULL    1500    98835
2014-05-07 00:00:00 4500    100 N   NULL    4500    103335
2014-05-09 00:00:00 750 100 N   NULL    750 104085
2014-05-13 00:00:00 540 100 N   NULL    540 104625

0 个答案:

没有答案