【问题标题】:SQL Query - Case When Min - Closest date to todaySQL 查询 - 最小的情况 - 到今天的最近日期
【发布时间】:2018-06-06 13:01:55
【问题描述】:

我有一张包含客户协议列表的表格[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 财年上半年

我在下面包含了我尝试过的查询。我想我需要第二个 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

【问题讨论】:

    标签: sql


    【解决方案1】:

    这个怎么样:

    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
    

    表格内容及结果如图:

    【讨论】:

    • 我认为你可以去掉 GROUP BY 子句。
    • Yes Vashi...你可以去掉 GROUP BY 子句
    • 啊,是的,对不起,我时间紧迫,最后一分钟删除了 MIN(),但忘记删除之前需要的 GROUP BY。好电话。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-16
    • 1970-01-01
    • 1970-01-01
    • 2021-07-30
    • 1970-01-01
    • 2016-03-28
    相关资源
    最近更新 更多