我可以使用以下查询保持运行总计,并且它就可以了。我真正想要的是,当间隙字段大于或等于date_diff字段时,运行总计应该重置回当前的hrly_qty。我确信我可以用光标实现我的结果,但我想知道可能的其他方法。想法?
示例:
WITH CTE AS
(
SELECT a.*, SUM(b.hrly_qty) AS running_total, c.gap
FROM #tmpTrxhist2 a
INNER JOIN #tmpTrxhist2 b ON a.people_id = b.people_id
AND b.sequence_id <= a.sequence_id
INNER JOIN incent_level c ON a.owner_division_id = c.owner_division_id
GROUP BY a.date_diff, a.owner_division_id, a.people_id, a.sequence_id,
a.hrly_qty, c.gap
)
SELECT * FROM CTE
ORDER BY people_id, sequence_id
答案 0 :(得分:-2)
你很少需要光标!一个简单的案例陈述就足够了。在我的头脑中有类似的东西:
WITH CTE AS
(
SELECT a.*, SUM(b.hrly_qty) AS running_total, c.gap
FROM #tmpTrxhist2 a
INNER JOIN #tmpTrxhist2 b ON a.people_id = b.people_id
AND b.sequence_id <= a.sequence_id
INNER JOIN incent_level c ON a.owner_division_id = c.owner_division_id
GROUP BY a.date_diff, a.owner_division_id, a.people_id, a.sequence_id,
a.hrly_qty, c.gap
)
SELECT *,
CASE
WHEN gap >= date_diff then hrly_qty else gap
END as comp_gap
FROM CTE
ORDER BY people_id, sequence_id
在两者之间运行执行计划,但SQL尝试优化非游标代码几乎总是更快乐。至少在我的领域,你通常会发现游标被“适当的”C / C ++程序员过度使用和滥用,因为当看到看似有点像while循环而不是考虑数据集的东西时,它们会进入他们的舒适区域。有一个游标的地方,但这不是它!