SQL查询 - 具有不同部分的案例

时间:2017-12-25 00:47:27

标签: sql

我需要计算协议属于财政年度的一半。

如果是7月到12月,那就是H1 如果是在1月到6月之间,则为H2

作为一个说明,协议可以持续多年,所以我使用AgreementEndDate今天关闭以确定财政年度。这部分代码有效(即min(case when AgreementEndDate>=@dtDate then AgreementEndDate else '' end) as 'Agreement End Date'

然而,这是我遇到问题的地方。我需要在“协议窗口”的末尾添加H1或H2。还没有想到它。

我尝试添加多个WHEN子句,但是,我得到重复的行。这就是为什么我一起去。

有什么建议吗?

DECLARE @dtDate DATE
SET @dtDate = GETDATE();
Select 
    AD.TPID
    ,min(case when AgreementEffectiveDate<=@dtDate then AgreementEffectiveDate else '' end) as 'Agreement Effective Date'
    ,min(case when AgreementEndDate>=@dtDate then AgreementEndDate else '' end) as 'Agreement End Date'
    ,min(case when AgreementEndDate>=@dtDate then 'FY' + convert(varchar(2),(FORMAT(AgreementEndDate, 'yy') - 1)) + ' H2'
            --WHEN (month(AgreementEndDate) >= 1 and month(AgreementEndDate) <= 6)  THEN 'FY' + convert(varchar(2),(FORMAT(AgreementEndDate, 'yy') - 1)) + ' H2'
            --WHEN (month(AgreementEndDate) >= 7 and month(AgreementEndDate) <= 12)  THEN 'FY' + convert(varchar(2),(FORMAT(AgreementEndDate, 'yy') - 1)) + ' H1'
            else '' end) as 'Agreement Window'
   from AgreementDetails AD

1 个答案:

答案 0 :(得分:0)

我明白了......这是解决方案。

,min(case   when AgreementEndDate>=@dtDate  and ((month(AgreementEndDate) >= 1 and month(AgreementEndDate) <= 6))  THEN 'FY' + convert(varchar(2),(FORMAT(AgreementEndDate, 'yy') - 1)) + ' H2'
            when AgreementEndDate>=@dtDate  and ((month(AgreementEndDate) >= 7 and month(AgreementEndDate) <= 12))  THEN 'FY' + convert(varchar(2),(FORMAT(AgreementEndDate, 'yy') - 1)) + ' H1'
        else '' end) as 'Agreement Window'