【发布时间】:2022-01-22 22:11:57
【问题描述】:
我已附上示例数据。这里实际上我想一起计算 emp_contribution 和 vpf 列的运行总数。但是,这应该在一个财政年度内。假设 2015 年将从 2015 年 4 月到 2016 年 3 月开始。这就是我面临挑战的地方。
下面我附上了我的尝试查询,但在 where 子句过滤器下工作不完美
select
case when sum(isnull(emp_contribution,0)) over(partition by emp_no order by pcm_month) + sum(isnull(vpf,0)) over(partition by emp_no order by pcm_month) < 3000
then sum(isnull(emp_contribution,0)) over(partition by emp_no order by pcm_month) + sum(isnull(vpf,0)) over(partition by emp_no order by pcm_month)
else null
end empcontbtnwithouttax,
case
when sum(isnull(emp_contribution,0)) over(partition by emp_no order by pcm_month) + sum(isnull(vpf,0)) over(partition by emp_no order by pcm_month) >= 3000
then sum(isnull(emp_contribution,0)) over(partition by emp_no order by pcm_month) + sum(isnull(vpf,0)) over(partition by emp_no order by pcm_month)
else null
end empcontbtnwithtax,
pcm_month, pcm_year, emp_no
from
[dbo].[pf_contribution_master]
where
(pcm_year >= 2015 and pcm_month >= 4 )
and (pcm_year <= 2016 and pcm_month < 4 )
and emp_no= 11101201
order by
pcm_year, pcm_month
【问题讨论】:
-
(pcm_year >= 2015 and pcm_month >= 4 )是“如果年份是 2015 或 2016 并且月份是四月或更晚”。(pcm_year <= 2016 and pcm_month < 4 )是“如果年份是 2015 或 2016 并且月份是四月之前”。看到问题了吗? -
@HABO 我已经尝试过了,但重复获得的记录数量更多。这对我不起作用。
-
我在用 your 代码解释问题。 (您在不知道为什么您的代码不起作用的情况下接受了答案。)您想要的是更像
( ( pcm_year = 2015 and pcm_month >= 4 ) or ( pcm_year = 2016 and pcm_month < 4 ) ) and emp_no= 11101201;的东西。请注意,此逻辑不会优雅地扩展到不相邻的年份,例如( ( pcm_year = 2010 and pcm_month >= 4 ) or ( 2010 < pcm_year and pcm_year < 2020 ) or ( pcm_year = 2020 and pcm_month < 4 ) ) and emp_no= 11101201;处理这些年。
标签: sql sql-server tsql