运行 总计上限
Running Total with cap
这是包含 50% 佣金和 50 美元上限的发票报告的数据示例。我正在使用 SQL Server 2008。我想我需要的是 运行 总上限列来生成我需要的结果。
这是一些示例数据:
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
因此,在 2017 年 2 月 2 日,我达到了 50 美元的上限,而在 2017 年 3 月 3 日,我无法再从该帐户中收款,因此金额将为 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
感谢我能得到的任何帮助。
一种方法是使用相关子查询来计算 运行 总数。我在下面的 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
这是包含 50% 佣金和 50 美元上限的发票报告的数据示例。我正在使用 SQL Server 2008。我想我需要的是 运行 总上限列来生成我需要的结果。 这是一些示例数据:
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
因此,在 2017 年 2 月 2 日,我达到了 50 美元的上限,而在 2017 年 3 月 3 日,我无法再从该帐户中收款,因此金额将为 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
感谢我能得到的任何帮助。
一种方法是使用相关子查询来计算 运行 总数。我在下面的 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