在SQL中根据日期标记某些行

时间:2018-07-05 19:09:34

标签: mysql sql sorting date

我目前有标有特定日期的数据。我想通过添加一列来对数据进行排序,该列指出日期是在上个月内,在过去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解决方案吗?谢谢!

2 个答案:

答案 0 :(得分: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;

答案 1 :(得分:0)

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;