SQL Sum和自我联接?

时间:2020-01-29 15:21:58

标签: sql sql-server

我在表T_FORECAST中组织了以下数据

   Location     Sublocation     Delivery_forecast    Delivery_Date     Forecast_date
   ----------------------------------------------------------------------------------
   1            1               100                  2020-01-01        2019-01-01
   1            2               50                   2020-01-01        2019-05-01
   1            1               90                   2020-01-01        2019-06-01
   1            2               70                   2020-01-01        2019-10-01
   . . .

我正在尝试编写一个查询,该查询将输出每个位置的Delivery_forecast的总和,Delivery_date和Forecast_date。 在下面的示例中,我期望:

   Location     Delivery_forecast    Delivery_Date     Forecast_date
   ----------------------------------------------------------------------------------
   1            100                  2020-01-01        2019-01-01
   1            150                  2020-01-01        2019-05-01
   1            140                  2020-01-01        2019-06-01
   1            160                  2020-01-01        2019-10-01

我可以使用下面的请求找到我需要的行的列表,但是我找不到正确的总和的方法。我相信我必须做一个自我加入

SELECT DISTINCT f.Location, f.Delivery_Date, f.Forecast_date
FROM T_FORECAST f 

3 个答案:

答案 0 :(得分:0)

使用累计金额:

select f.*,
       sum(delivery_forecast) over (partition by location, delivery_date order by forecast_date) as running_delivery_forecast
from T_FORECAST f;

答案 1 :(得分:0)

首先,您希望聚合以获取每个位置和日期的总和(SUM(delivery_forecast) / GROUP BY LOCATION, DELIVERY_DATE, FORECAST_DATE)。然后,您想要显示运行总计(SUM OVER)。我猜每个位置。两者相结合:

select 
  location,
  delivery_date,
  forecast_date,
  sum(delivery_forecast) as forcast_for_day,
  sum(sum(delivery_forecast)) over (partition by location
                                    order by delivery_date, forecast_date
                                   ) as forcast_cumulated
from t_forecast
group by location, delivery_date, forecast_date
order by location, delivery_date, forecast_date;

答案 2 :(得分:0)

问题的关键在于,您要始终从连续两行中添加值。

为此,您可以根据您的特定订购使用“窗框”。参见SQL Server - Over clause

例如:

select
  location,
  sum(delivery_forecast) over(
    partition by location, delivery_date 
    order by forecast_date
    rows between 1 preceding and current row -- the magic is here!
  ) as delivery_forecast,
  delivery_date, 
  forecast_date
from t_forecast
group by location, delivery_date, forecast_date