需要生成2个运行的总列,每个列基于不同的分组。我希望解决方案使用OUTER APPLY方法,如下所示,除了修改为在不同的group by / columns上运行多个运行总计/ sum。有关所需结果的示例,请参见图像
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;
示例+欲望结果: i.stack.imgur.com/PvJQe.png
答案 0 :(得分:1)
两次使用outer apply
:
以下是如何获得一个总计:
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;
对于两个,您只需添加另一个OUTER APPLY
。您的问题未指定第二个聚合是什么,并且链接的图片与问题中的描述无关。
注意: