在sql中基于日期标记某些行

3bygqnnd  于 2021-06-20  发布在  Mysql
关注(0)|答案(2)|浏览(236)

我目前有一个特定日期标记的数据。我想通过添加一个列来对这些数据进行排序,该列说明日期是在上个月内、在最近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解决方案,可以像这样标记和排序日期?谢谢!

fsi0uk1n

fsi0uk1n1#

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;
ny6fqffe

ny6fqffe2#

你会使用 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;

相关问题