【问题标题】:SQL Server query to filter the financial year when month and year are in different columns当月份和年份在不同列中时,SQL Server 查询过滤财政年度
【发布时间】: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 &gt;= 2015 and pcm_month &gt;= 4 ) 是“如果年份是 2015 或 2016 并且月份是四月或更晚”。 (pcm_year &lt;= 2016 and pcm_month &lt; 4 ) 是“如果年份是 2015 或 2016 并且月份是四月之前”。看到问题了吗?
  • @HABO 我已经尝试过了,但重复获得的记录数量更多。这对我不起作用。
  • 我在用 your 代码解释问题。 (您在不知道为什么您的代码不起作用的情况下接受了答案。)您想要的是更像( ( pcm_year = 2015 and pcm_month &gt;= 4 ) or ( pcm_year = 2016 and pcm_month &lt; 4 ) ) and emp_no= 11101201; 的东西。请注意,此逻辑不会优雅地扩展到不相邻的年份,例如( ( pcm_year = 2010 and pcm_month &gt;= 4 ) or ( 2010 &lt; pcm_year and pcm_year &lt; 2020 ) or ( pcm_year = 2020 and pcm_month &lt; 4 ) ) and emp_no= 11101201; 处理这些年。

标签: sql sql-server tsql


【解决方案1】:

在这种特定情况下出现意外结果的实际原因是WHERE 子句的(pcm_year &gt;= 2015 and pcm_month &gt;= 4) and (pcm_year &lt;= 2016 and pcm_month &lt; 4) 部分,其中第二个AND 运算符的使用是错误的。

在这种情况下,您可以考虑进行额外的计算和不同的WHERE 子句:

...
WHERE 
   (pcm_year * 100 + pcm_month >= 201504) AND
   (pcm_year * 100 + pcm_month < 201604) AND
   (emp_no = 11101201)
...

【讨论】:

  • 一个足够模糊的编辑。这三个中是否有任何特定的and 可能有问题?
  • 您是否建议(pcm_year &gt;= 2015 and pcm_month &gt;= 4) OR (pcm_year &lt;= 2016 and pcm_month &lt; 4) 允许任何 年的一些数据来解决OP 的问题?或者是否有其他运算符可以替换第二个AND?另外:如果性能是一个问题,那么可以为pcm_year * 100 + pcm_month 添加一个持久计算列并建立索引。
  • @HABO,当然不是。将第二个AND 替换为OR 并不是一个通用的解决方案。
猜你喜欢
  • 2014-04-26
  • 2020-07-20
  • 2015-07-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多