MySQL:基于日期范围的计算列

MySQL: Calculated Column Based on Date Range

如何创建一个计算列,如果日期在 2015 年内则生成值 1,否则为 0?

我昨天用谷歌搜索和搜索 Whosebug,寻找解决方案无济于事。根据我对 CASE WHEN、BETWEEN 和 CAST 的了解,我整理了以下 SQL 脚本。

然而,尽管在 2015 年、2016 年有相应的 Prescreen 日期,甚至日期为 0000-00-00,但下面的(截断的)脚本产生全 0,如下所示:

SELECT 
table_r.R_Number,
table_c.ref_num,
DATE(STR_TO_DATE(table_c.Prescreen, '%d-%b-%y')) AS Prescreen,
CASE
    WHEN Prescreen BETWEEN CAST('2015-01-01' AS DATE) AND CAST('2015-12-31' AS DATE) THEN 1
    ELSE 0
END AS YTD2015_Prescreen,
table_r.Region,
FROM
table_c
    INNER JOIN
table_r ON table_c.R_Number = table_r.R_Number
WHERE
table_c.Int <> ''
;

我谦虚地请求你把你的天才借给我。谢谢你。 :)

试试这个:

    SELECT 
    table_r.R_Number,
    table_c.ref_num,
    STR_TO_DATE(table_c.Prescreen,'%d-%b-%y') AS Prescreen,
    CASE
    WHEN STR_TO_DATE(table_c.Prescreen,'%d-%b-%y')  BETWEEN CAST('20150101'AS DATE) AND CAST('20151231' AS DATE) THEN 1
    ELSE 0
    END AS YTD2015_Prescreen,
    table_r.Region,
    FROM
    table_c
        INNER JOIN
    table_r ON table_c.R_Number = table_r.R_Number
    WHERE
    table_c.Int <> ''
    ;