基于指标列SQL Server运行总计

时间:2018-01-28 08:55:38

标签: sql sql-server data-warehouse

我想计算当FuelIndicator从NotReserve切换到Reserve时累计的运行总计。任何人都可以建议我将如何实现这一目标吗?

FuelDate    FilledBy    KMSreading  FuelAmt FuelPrice   Vehicle         FuelIndicator
2017-04-12  Acb         34040       200     71.29       Suzuki GS150R   Reserve
2017-04-17  Acb         34142       200     71.29       Suzuki GS150R   Reserve
2017-04-20  Acb         34246_______200_____72.97_______Suzuki GS150R   Not Reserve
2017-04-24  Acb         34350_______200_____72.97_______Suzuki GS150R   Not Reserve
2017-04-28  Acb         34365_______100_____72.97_______Suzuki GS150R   Reserve
2017-04-30  Acb         34500       100     72.97       Suzuki GS150R   Reserve
2017-05-03  Acb         34620       250     75.20       Suzuki GS150R   Reserve

预期产出:

FuelDate    FilledBy    KMSreading  FuelAmt FuelPrice   Vehicle         FuelIndicator
2017-04-12  Acb         34040       200     71.29       Suzuki GS150R   Reserve
2017-04-17  Acb         34142       200     71.29       Suzuki GS150R   Reserve
2017-04-28  Acb         34365_______500_____72.97_______Suzuki GS150R   Reserve
2017-04-30  Acb         34500       100     72.97       Suzuki GS150R   Reserve
2017-05-03  Acb         34620       250     75.20       Suzuki GS150R   Reserve

谢谢,

1 个答案:

答案 0 :(得分:0)

你似乎想要结合"不要保留"以下"保留" s。这似乎假设所有其他列是相同的,除了燃料amt,kms读数和日期。

您需要定义一个组。在这种情况下,困难的部分是获得额外的"储备"与之前的"不保留" s。关键的想法是总结"储备"从每行到数据末尾的值。此方法将根据您的需要分配组:

select t.*,
       sum(case when fuelindicator = 'Reserve' then 1 else 0 end) over (partition by vehicle order by fueldate desc) as grp
from t;

一旦我们进行了分组,剩下的就是聚合:

select max(fueldate) as fueldate, FilledBy, max(KMSreading) as KMSreading,
       sum(FuelAmt) as fuelamt, FuelPrice, Vehicle,
       'Reserve' as fuelindicator
from (select t.*,
             sum(case when fuelindicator = 'Reserve' then 1 else 0 end) over (partition by vehicle order by fueldate desc) as grp
      from t
     ) t
group by FilledBy, FuelPrice, Vehicle ;