我有一个表包含两个列一个月,另一个列表示一年。基于这两列,我想要该财政年度的所有记录。例如。如果月份是10年,而年份是2014年那么其他财政年度将是2014年4月1日至2015年3月31日。
如何编写SQL select查询以获取在该表中基于月份和年份在FY 01stApr14-31stMar15之间创建的所有记录。
M尝试以下查询,但在关键字'和'''
附近出现错误信息错误。'with cte as
(
select id,iono,iomonth,ioyear,
convert(datetime,'01/'+right('00' + convert(varchar(10),iomonth,2),2)
+ '/' +convert(varchar(4),IOyear),103) as FinDate from iodetails where iono=12345
)
select month(findate),* from cte where iono=12345 and
findate between
case
when month(findate)>=4
then convert(datetime,'01/'+'04'+ '/' +convert(varchar(4),IOyear),103) and
convert(datetime,'31/'+ '03' + '/' +convert(varchar(4),IOyear+1),103)
else
convert(datetime,'01/'+'04'+ '/' +convert(varchar(4),IOyear),103) and
convert(datetime,'31/'+ '03' + '/' +convert(varchar(4),IOyear),103)
end
答案 0 :(得分:1)
如果我理解您的要求,您可以尝试这样做:
SELECT * FROM mytable
WHERE year(dateadd(q, -1, mydate)) = 2014
这将从mydate
的值中减去1个季度(3个月)并提取年份。因此,31 Mar 2015
在减法后变为31 Dec 2014
,提取年份时为2014年。
哎呀道歉,我看到你有两列,一个月和一年。在这种情况下,你可以试试这个:
SELECT * FROM mytable
WHERE year(dateadd(q, -1, cast(cast(mymonth AS char) + '/01/' + cast(myyear AS char) AS datetime))) = 2014
然而,这可能不是最有效的方法。
根据我的评论更新
以下是在表格中创建计算列的方法:
ALTER TABLE mytable
ADD mydate AS cast(cast(mymonth AS char) + '/01/' + cast(myyear AS char) AS datetime)
答案 1 :(得分:1)
试试这个:
SELECT *
FROM tableA
WHERE CAST((CAST(YearCol AS VARCHAR(10)) + (CAST(MonthCol AS VARCHAR(10))) AS INT)
BETWEEN CAST((CASE WHEN @V_Month BETWEEN 4 AND 12 THEN CAST((CAST(@V_Year AS VARCHAR(10)) + '04') AS INT)
WHEN @V_Month BETWEEN 1 AND 3 THEN CAST((CAST(@V_Year - 1 AS VARCHAR(10)) + '04') AS INT)
ELSE ''
END
) AS INT)
AND CAST((CASE WHEN @V_Month BETWEEN 4 AND 12 THEN CAST((CAST(@V_Year + 1 AS VARCHAR(10)) + '03') AS INT)
WHEN @V_Month BETWEEN 1 AND 3 THEN CAST((CAST(@V_Year AS VARCHAR(10)) + '03') AS INT)
ELSE ''
END
) AS INT);