SQL查询 - 最小时的情况 - 到今天的最近日期

时间:2017-12-25 05:02:58

标签: sql

我有一张表格,其中列有客户协议[source.Agreements] 客户可以拥有多个具有不同[Agreement End Date]

的协议

我需要获得最接近的[Agreement End Date],然后将其分配给[Agreement Window]

例如:

如果在1月至6月之间:

  

[Agreement Window] = FY H2

如果在7月到12月之间那么:

  

[Agreement Window] = FY H1。

财政年度=([Agreement End Date] - 1年)

示例:

ID[Agreement End Date] = 2020-06-30。所以,[Agreement Window] = 'FY19 H2'

但是,当ID有多个[Agreement End Date],而第二个日期是7月到12月之间时,它会使用该日期而不是MIN日期。

示例:(见下图)

ID 1789有三个[Agreement End Date] = '2018-05-31', '2018-09-30', '2019-03-30' 它应该返回:

  

2017财年下半年

但它返回

  

2017财年上半年

enter image description here

我已经包含了我在下面尝试的查询。我想我需要第二个MIN声明,但不知道如何使用CASE声明。

DECLARE @dtDate DATE
SET @dtDate = GETDATE();

select A.ID 
    ,min(case when AgreementEndDate>=@dtDate then AgreementEndDate else '' end) as 'Agreement End Date'
    ,min(case when AgreementEndDate>=@dtDate  and ((month(AgreementEndDate) >= 7 and month(AgreementEndDate) <= 12))  THEN 'FY' + convert(varchar(2),(FORMAT(AgreementEndDate, 'yy') - 1)) + ' H1'
              when AgreementEndDate>=@dtDate  and ((month(AgreementEndDate) >= 1 and month(AgreementEndDate) <= 6))   THEN 'FY' + convert(varchar(2),(FORMAT(AgreementEndDate, 'yy') - 1)) + ' H2'
        else null end) as 'Agreement Window'
from source.Agreements A
where A.ID IN ('1740','1789','7582645','2387732')
group by A.ID

1 个答案:

答案 0 :(得分:0)

这个怎么样:

DECLARE @dtDate DATE

SET @dtDate = GETDATE();

WITH cte
AS (
    SELECT *, ROW_NUMBER() OVER (
            PARTITION BY ID ORDER BY AgreementEndDate ASC
            ) AS RowNum
    FROM [source].[dbo].Agreements A
    WHERE A.ID IN ('1740', '1789', '7582645', '2387732')
    )
SELECT ID
    , CASE WHEN AgreementEndDate >= @dtDate THEN AgreementEndDate ELSE '' END AS 'Agreement End Date'
    , CASE WHEN AgreementEndDate >= @dtDate AND ((month(AgreementEndDate) >= 7 AND month(AgreementEndDate) <= 12)) THEN 'FY' + convert(VARCHAR(2), (FORMAT(AgreementEndDate, 'yy') - 1)) + ' H1' 
    WHEN AgreementEndDate >= @dtDate AND ((month(AgreementEndDate) >= 1 AND month(AgreementEndDate) <= 6)) THEN 'FY' + convert(VARCHAR(2), (FORMAT(AgreementEndDate, 'yy') - 1)) + ' H2' 
    ELSE NULL 
    END AS 'Agreement Window'
FROM cte
WHERE RowNum = 1

表格内容和结果如下所示:

example