简体   繁体   English

MS SQL-多个运行总计,每个总计基于不同的GROUP BY

[英]MS SQL - Multiple Running Totals, each based on a different GROUP BY

Need to generate the 2 running total columns which are each based on a different group-by. 需要生成2个运行总计列,每个列基于不同的分组依据。 I would PREFER that the solution use the OUTER APPLY method like the one below, except modified to run multiple running totals/sums on different group bys/columns. 我希望该解决方案使用如下所示的OUTER APPLY方法,但修改后可以在不同的分组依据/列上运行多个运行总计/总和。 See image for example of desired result 参见图片以了解所需结果

SELECT t1.LicenseNumber, t1.IncidentDate, t1.TicketAmount, 
  RunningTotal = SUM(t2.TicketAmount)
FROM dbo.SpeedingTickets AS t1
OUTER APPLY
(
  SELECT TicketAmount 
    FROM dbo.SpeedingTickets 
    WHERE LicenseNumber = t1.LicenseNumber
    AND IncidentDate <= t1.IncidentDate
) AS t2
GROUP BY t1.LicenseNumber, t1.IncidentDate, t1.TicketAmount
ORDER BY t1.LicenseNumber, t1.IncidentDate;

Example + desires result: i.stack.imgur.com/PvJQe.png 示例+期望结果: i.stack.imgur.com/PvJQe.png

Use outer apply twice: 使用outer apply两次:

Here is how you get one running total: 这是获得总计的方式:

SELECT st.*, r1.RunningTotal
FROM dbo.SpeedingTickets st OUTER APPLY
     (SELECT SUM(st2.TicketAmount) as RunningTotal
      FROM dbo.SpeedingTickets st2
      WHERE st2.LicenseNumber = st.LicenseNumber AND
            st2.IncidentDate <= st.IncidentDate
     ) r1
ORDER BY st.LicenseNumber, st.IncidentDate;

For two, you just add another OUTER APPLY . 对于两个,您只需添加另一个OUTER APPLY Your question doesn't specify what the second aggregation is, and the linked picture has no relevance to the description in the question. 您的问题未指定第二个聚合是什么,并且链接的图片与问题中的描述无关。

Notes: 笔记:

  • The aggregation goes in the subquery, not in the outer query. 聚合在子查询中进行,而不在外部查询中进行。
  • Use table abbreviations for table aliases. 使用表缩写作为表别名。 Such consistency makes it easier to follow the query. 这样的一致性使跟踪查询变得更加容易。
  • When using correlated subqueries, always use qualified column names for all columns. 使用关联子查询时,请始终对所有列使用合格的列名。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM