计算运行总计和运行总计详细信息

时间:2018-10-25 09:29:42

标签: sql sql-server-2012

在下表中,我需要获取运行总计以及运行总计的详细信息。

running total and details of running total

例如,在此表中的person_id = 12

  

摘要:

     
      
  • 在2018-10-19 21:23:00.567分配了Transaction_Type并且MACHINECOUNT = 1,因此到那时分配的计算机总数为1

  •   
  • 在2018-10-19 21:23:17.077分配Transaction_Type并且MACHINECOUNT = 1,并且到那时分配的计算机总数为2

  •   
  • 在2018-10-19 21:26:33.513分配Transaction_Type并且MACHINECOUNT = 1,并且到那时分配的计算机总数为3

  •   
  • 于2018-10-19 21:26:58.980 Transaction_Type为unassign并且MACHINECOUNT = 1,并且到那时分配的计算机总数为2,依此类推   在

  • 上   
     

在详细信息方面:

     
      
  • 在第二行上,machinecount为2,所以我需要包括哪些batch_run_step_ids以获得计数

  •   
  • 在第三行上,计算机计数为3,所以我需要包括哪些批处理运行步骤以获取计数,依此类推

  •   

summary

我可以通过人员使用sum函数进行分区来获取摘要,但是我需要获取machinecount的详细信息。例如,在摘要屏幕截图中,按时间分配的第二排计算机是2,我需要这两台计算机的详细信息,即要获得总和需要包括哪些步骤/行。

expected details for first four records in summary

2 个答案:

答案 0 :(得分:0)

对于第一个查询,您需要对SUM()语句中的MACHINECOUNT使用select Window Function ,如下所示:

摘要查询:

select
    [your_columns],
    sum((case Transaction_Type when 'assign' then MACHINECOUN when 'unassign' then MACHINECOUN * -1 end))
    over(partition by personnel_id order by DATE_TIME)  as [RunningTotal]
from
    [your_table]

答案 1 :(得分:0)

如果我理解正确,则需要累积条件和:

select t.*,
       sum(case when transaction_type = 'assign' then 1
                when transaction_type = 'unassign' then -1
                else 0
           end) over (partition by personnel_id
                      order by date_time
                     ) as machine_assigned_by_time
from t;