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

时间:2016-02-09 20:54:41

标签: mysql sql date case between

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

我昨天用谷歌搜索,并搜索StackOverflow,寻找解决方案无济于事。根据我对CASE WHEN,BETWEEN和CAST的了解,我将下面的SQL脚本放在一起。

然而,下面(截断的)脚本会产生所有0,尽管在2015年,2016年甚至是0000-00-00的日期都有相应的预览日期,如下所示: enter image description here

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

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

1 个答案:

答案 0 :(得分:0)

试试这个:

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