【问题标题】:Tagging certain rows based on date in SQL在 SQL 中根据日期标记某些行
【发布时间】:2018-07-05 19:09:34
【问题描述】:

我目前有带有特定日期标记的数据。我想通过添加一列来对这些数据进行排序,该列说明日期是在上个月内、在过去 2-3 个月内还是在 3 个月内。

目前我的日期存储在这样的表中:

 Date
 ----
 06/28/2018
 06/21/2018
 05/19/2014
 05/02/2018

我希望数据看起来像这样:

 Date          DateTag
 ----          -------
 06/28/2018    Last Month
 06/21/2018    Last Month
 05/19/2014    Over 3 Months
 05/02/2018    Last 3 Months

有没有人有关于如何像这样标记和按日期排序的 SQL 解决方案?谢谢!

【问题讨论】:

    标签: mysql sql sorting date


    【解决方案1】:

    您将使用case 表达式:

    select date,
           (case when date <= curdate() and date > curdate() - interval 1 month
                 then 'within 1 month'
                 when date <= curdate() - interval 1 month and date > curdate() - interval 2 month
                 then '2-3 months ago'
                 when date <= curdate() - interval 3 month
                 then '3+ months ago'
            end)
    from t;
    

    【讨论】:

    • 我遇到了这个声明 curdate() - interval 1 month 的问题,我的日期格式可能不允许运行这个声明吗?
    • @BobDuncan date 字段的数据类型应为 DATEDATETIME
    • 如果不是,则需要使用STR_TO_DATE()来解析。
    • @BobDuncan 。 . . curdate() - interval 1 month 绝对适用于 MySQL,并且有很多很多版本。
    • @Barmar STR_TO_DATE() 方法解决了我的问题,我没有使用正确 DATE 数据类型的日期字段。非常感谢。
    【解决方案2】:
    CREATE TABLE test_dates (
        date DATE
    );
    
    insert into test_dates values('2018-06-28'),('2018-06-21'),('2014-05-19'),('2018-05-02');
    
    SELECT 
        date,
        CASE
            WHEN date BETWEEN DATE_ADD(NOW(), INTERVAL - 30 DAY) AND NOW() THEN 'Last Month'
            WHEN date BETWEEN DATE_ADD(NOW(), INTERVAL - 90 DAY) AND NOW() THEN 'Last 3 Months'
            WHEN date < DATE_ADD(NOW(), INTERVAL - 30 DAY) THEN 'Over 3 Months'
        END AS DateTag
    FROM
        test_dates;
    

    【讨论】:

    • 跑了这个,但每一个项目都被标记为“超过 3 个月”
    猜你喜欢
    • 1970-01-01
    • 2021-11-25
    • 2016-05-05
    • 1970-01-01
    • 1970-01-01
    • 2015-10-03
    • 1970-01-01
    • 1970-01-01
    • 2021-01-14
    相关资源
    最近更新 更多