如何计算一列SQL的总和?

How to calculate the sum of a column SQL?

需要一些帮助。

我的Table如下->

Project_Name Date Recorded_Hours Planned_Hours Remaining_Hours
Civil 06-03-2022 5 10 5
Civil 07-03-2022 3 7 4
Civil 08-03-2022 9 9 0
Civil 09-03-2022 4 10 6
Civil 10-03-2022 8 5 -3
Civil 11-03-2022 8 8 0
Civil 12-03-2022 0 5 -5
Civil 13-03-2022 0 4 -4
Civil 14-03-2022 0 3 -3
Civil 15-03-2022 0 4 -4
Civil 15-03-2022 0 5 -5

这里我只有一个项目,但实时我有多个项目。

In this table Recorded_Hours is total hours done per day, Planned_Hours is total hours planned per day and Remaining_Hours is ( Planned_Hours - Recorded_Hours ). I want to sum all the Remaining_Hours till today then distribute that sum evenly to each future Planned_Hours.

In this above table total sum of Remaining_Hours till today is 12 and there is 5 Days left to complete this project. I want to add 12/5 to each 5 Days left Planned_Hours. This should automatically calculate everyday.

我的输出将是 ->

Project_Name Date Recorded_Hours Planned_Hours Remaining_Hours
Civil 06-03-2022 5 10 5
Civil 07-03-2022 3 7 4
Civil 08-03-2022 9 9 0
Civil 09-03-2022 4 10 6
Civil 10-03-2022 8 5 -3
Civil 11-03-2022 8 8 0
Civil 12-03-2022 0 7.4 -7.4
Civil 13-03-2022 0 6.4 -6.4
Civil 14-03-2022 0 5.4 -5.4
Civil 15-03-2022 0 6.4 -6.4
Civil 15-03-2022 0 7.4 -7.4

到此为止

SELECT 
 [Project_Name]= CASE WHEN GROUPING(Date) = 0 THEN [Project_Name]ELSE 'Total' END,
  Date,
  [Remaining_Hours] = SUM([Planned_Hours]-[Recorded_Hours])
FROM[dbo].[Projects]

GROUP BY GROUPING SETS (
    ([Project_Name], Date),
    ([Project_Name]));

首先,您找到每个项目截至今天的总剩余小时数 (GROUP BY)

select Project, Total_Remaining_Hours = sum(Remaining_Hours),
from   Projects
where  [Date] <= @today 
group by Project

那你还需要剩余天数

select Project, Remaining_Days = count(*)
from   Projects
where  [Date] > @today 
group by Project

将它们组合在一起(INNER JOIN)并使用 CASE 表达式来检查,忽略过去的日期,只调整未来的日期

declare @today date = getdate();

select *,
       New_Planned_Hours = case when p.[Date] <= @today
                                then p.Planned_Hours
                                else p.Planned_Hours 
                                +    (t.Total_Remaining_Hours / d.Remaining_Days)
                                end
from   Projects p
       inner join
       (
          select Project,
                 Total_Remaining_Hours = sum(Remaining_Hours)
          from   Projects
          where  [Date] <= @today
          group by Project
       ) t  on p.Project = t.Project
       inner join
       (
          select Project,
                 Remaining_Days = count(*)
          from   Projects
          where  [Date] > @today
          group by Project
       ) d  on p.Project = d.Project
order by p.Project, p.[Date]

db<>fiddle demo