DECLARE @ServDate DATE = '01/04/2013',
@PaidDate DATE = '01/25/2013'
SELECT @ServDate AS DATE ,@PaidDate AS PaidDate ,
CASE WHEN (MONTH(@ServDate) IN (9,10,11) AND MONTH(@PaidDate) IN (9,10,11)
AND YEAR(@ServDate) = YEAR(@PaidDate)) AND (convert(CHAR(4), YEAR(@ServDate))
= convert(CHAR(4), YEAR(@PaidDate)))
THEN 'FSY' + ''+ convert(CHAR(4), YEAR(@ServDate) + 1) + '-' + 'Q1'
WHEN (MONTH(@ServDate) IN (12,1,2) AND MONTH(@PaidDate) IN (12,1,2) AND
YEAR(@ServDate) = YEAR(@PaidDate)) AND ( (convert(CHAR(4), YEAR(@ServDate) + 1)
= convert(CHAR(4), YEAR(@PaidDate))) OR (convert(CHAR(4), YEAR(@ServDate))
= convert(CHAR(4), YEAR(@PaidDate))) )
THEN 'FSY' + ''+
CASE WHEN (MONTH(@ServDate) IN (1,2) AND MONTH(@PaidDate) IN (1,2)) AND
(convert(CHAR(4), YEAR(@ServDate)) = convert(CHAR(4), YEAR(@PaidDate)))
THEN convert(CHAR(4), YEAR(@ServDate) - 0) + '-' + 'Q2'
ELSE convert(CHAR(4), YEAR(@ServDate) + 1) + '-' + 'Q2'
END
WHEN (MONTH(@ServDate) IN (3,4,5) AND MONTH(@PaidDate) IN (3,4,5) AND
YEAR(@ServDate) = YEAR(@PaidDate)) AND (convert(CHAR(4), YEAR(@ServDate))
= convert(CHAR(4), YEAR(@PaidDate)))
THEN 'FSY' + ''+ convert(CHAR(4), YEAR(@ServDate) - 0)+ ' - '+ 'Q3'
WHEN (MONTH(@ServDate) IN (6,7,8) AND MONTH(@PaidDate) IN (6,7,8) AND
YEAR(@ServDate) = YEAR(@PaidDate)) AND (convert(CHAR(4), YEAR(@ServDate))
= convert(CHAR(4), YEAR(@PaidDate)))
THEN 'FSY' + ''+ convert(CHAR(4), YEAR(@ServDate) - 0) + ' - ' + 'Q4'
ELSE 'NQ'
END AS Quarter
我必须编写一个案例表达式来确定哪个季度日期也属于。
我们的公司季度开始Q1:ServDate = 9/01 / 2014& 2014年11月30日Piad Date 9/1/2014& 2014年11月30日将是FSY2015Q1
季度将填充如下:
Q1 - DOS 9/1 to 11/30
Q1 - Paid 9/1 to 11/30
Q2 - DOS 9/1 to 2/28
Q2 - Paid 9/1 to 2/28
Q3 - DOS 9/1 to 5/31
Q3 - Paid 9/1 to 5/31
Q4 - DOS 9/1 to 8/31
Q4 - Paid 9/1 to 8/31
所以让我们说ItemID 1 Servdate 9/01/2014付款日期11/30/2014将是FSY2015Q1
但是,如果我有一个记录,那么让我们说ItemID 1 Servdate 9/01/2014付费日期12/30/2014我需要它说“NQ”,这就是我失败的地方......
有人可以帮助我吗?
答案 0 :(得分:0)
这样做你想要的吗?
select choose(month(date), 'Q2', 'Q2', 'Q2', 'Q3', 'Q3', 'Q3, 'Q4', 'Q4', 'Q4', 'Q1', 'Q1', 'Q1')
month()
返回月份。这只是查看季度值,我认为从1月份的Q2开始。
注意:SQL Server 2012+中提供了choose()
。您可以在早期版本中使用case
语句执行相同的操作:
select (case month(date) when 1 then 'Q2'
when 2 then 'Q2'
. . .
end) as quarter
答案 1 :(得分:0)
只需将日期抵消适当的月数。您的要求的核心是这个表达:
'Q' + cast(datepart(qq, dateadd(mm, -4, <DATE>)) as char(1))
要获取您正在寻找的确切文本,只需使用季度数来驱动案例表达式。日期组件也可以计算,但我觉得它不值得硬编码的麻烦:
case datepart(qq, dateadd(mm, -4, <DATE>)
when 1 then 'Q1 ...'
when 2 then 'Q2 ...'
when 3 then 'Q3 ...'
when 4 then 'Q4 ...'
end