以下是50%佣金和50美元上限的发票报表数据样本。我正在使用SQL Server 2008.我认为我需要的是一个总计的cap列来产生我需要的结果。 以下是一些示例数据:
account|amount|transdate |commission|cap 123456 |50 |2017-01-01 00:00:00|25 |25 123456 |50 |2017-02-02 00:00:00|25 |25 123456 |100 |2017-03-03 00:00:00|50 |50
这是我想看到的:
account|amount|transdate |commission|cap|running_total 123456 |50 |2017-01-01 00:00:00|25 |25 |25 123456 |50 |2017-02-02 00:00:00|25 |25 |50 123456 |100 |2017-03-03 00:00:00|50 |50 |0
所以在2/2/17我已经达到50美元的上限,并且在3/3/17我不能长时间收集这个账户,因此金额将为0.
select account, amount, transdate, coalesce(amount*.5, 0) as commission, (case when coalesce(amount*.5, 0)>=50 then 50 else coalesce(amount*.5, 0) end) as cap from #invoice
感谢我能得到的任何帮助。
答案 0 :(得分:2)
一种方法是使用相关子查询来计算运行总计。我在下面的CTE中进行此计算,并且我报告在最终输出中运行总计,但总数小于上限,否则报告为零。
WITH cte1 AS (
SELECT
account,
amount,
transdate,
COALESCE(amount*0.5, 0) AS commission,
CASE WHEN COALESCE(amount*0.5, 0) >= 50
THEN 50 ELSE COALESCE(amount*0.5, 0) END AS cap
FROM #invoice
),
cte2 AS (
SELECT *,
(SELECT SUM(t2.cap) FROM cte1 t2
WHERE t2.transdate <= t1.transdate) AS running_total
FROM cte1 t1
)
SELECT
t.account,
t.amount,
t.transdate,
t.commission,
t.cap,
CASE WHEN t.running_total > 50 THEN 0 ELSE t.running_total END AS running_total
FROM cte2 t