我需要根据今天的日期在我的选择声明中包含会计年度,例如2016年至2016年12月30日。财政年度从7月1日开始。截至2017年7月1日,它应计算2017-2018。我怎么能做到这一点?
ClaimNo
20161030
20161124
20160815
20170115
20180101
SELECT *
FROM TABLE
WHERE ClaimNo LIKE '2016%' OR ClaimNo LIKE '2017%';
答案 0 :(得分:1)
DECLARE @ThisYear VARCHAR(50)
DECLARE @NextYear VARCHAR(50)
SET @ThisYear = CAST(DATEPART(YYYY,GETDATE()) as varchar(20)) +'0731' --print @ThisYear
SET @NextYear = CAST(DATEPART(YYYY,DATEADD(YYYY,1,GETDATE()))as varchar(20))+'1231' --print @Nextyear
SELECT * FROM TABLE WHERE CAST(ClaimNo AS DATE) BETWEEN @ThisYear and @NextYear
答案 1 :(得分:1)
SELECT ClaimNo,
CASE WHEN MONTH(CONVERT(DATE,ClaimNo)) <7 THEN YEAR(CONVERT(DATE,ClaimNo))
ELSE YEAR(CONVERT(DATE,ClaimNo)) + 1 END AS FiscalYear
FROM
<<Table>>;
测试代码
DECLARE @tab TABLE (ClaimNo CHAR(20));
INSERT INTO @tab (ClaimNo)
VALUES
('20161030'),
('20161124'),
('20160815'),
('20170115'),
('20180101');
SELECT ClaimNo,
CASE WHEN MONTH(CONVERT(DATE,ClaimNo)) <7 THEN YEAR(CONVERT(DATE,ClaimNo))
ELSE YEAR(CONVERT(DATE,ClaimNo)) + 1 END AS FiscalYear
FROM
@tab;
答案 2 :(得分:1)
在ad-hoc计数表的帮助下,我们可以轻松计算财政年度。在这种情况下,我们从1980年开始,接下来的50年。这两个项目都可以根据需要进行调整。
DECLARE @table TABLE (ClaimNo varchar(25));
INSERT INTO @table (ClaimNo)
VALUES
('20161030'),
('20161124'),
('20160815'),
('20170115'),
('20180101');
Select A.ClaimNo
,FiscalYear = Str(Year(D1),4)+' - '+Str(Year(D2),4)
From @table A
Join (
Select Top 50 D1=cast(DateAdd(YY,Row_Number() Over (Order By Number)-1,'1980-07-01') as Date)
,D2=cast(DateAdd(YY,Row_Number() Over (Order By Number),'1980-06-30') as Date)
From master..spt_values
) D
on ClaimNo Between D1 and D2
返回
ClaimNo FiscalYear
20161030 2016 - 2017
20161124 2016 - 2017
20160815 2016 - 2017
20170115 2016 - 2017
20180101 2017 - 2018
注意:如果ClaimNo是int,只需将ON子句更改为
即可on cast(ClaimNo as varchar(8)) Between D1 and D2