列中有两种不同的日期类型

时间:2015-06-19 14:08:14

标签: mysql sql date

我正在尝试在mysql中创建一个年龄组数组。

SELECT 
    COUNT(*),
    CASE 
        when age < 60 THEN '<60'
        when age >= 61 AND age <= 65 then '61-65'
        when age >= 66 AND age <= 70 then '66-70'
        when age >= 71 AND age <= 75 then '71-75'
        when age >= 76 AND age <= 80 then '76-80'
        when age > 81  then '>81'
    END as age_group

FROM( 
    SELECT YEAR(current_time()) - Year(DateBorn) AS age
    FROM custs
    WHERE  FDID = 'ANGL01'

) as custs2

GROUP BY age_group

当我运行此查询时,它工作正常,但有2013年的null结果。事实证明,该列中有2种数据格式。

第一个就是这一年:&#39; yyyy&#39;

第二个包括日期和月份:&#39; dd / mm / yyyy&#39;

如何修改此查询以同时考虑这两种数据格式?

4 个答案:

答案 0 :(得分:1)

理想情况下,您应使用DATE数据类型存储日期。

根据您当前的架构,假设日期总是以yyyy或dd / mm / yyyy格式,那么年份将始终是最右边的4个字符,因此您可以使用RIGHT(DateBorn,4) ,像这样:

SELECT 
    COUNT(*),
    CASE 
        when age < 60 THEN '<60'
        when age >= 61 AND age <= 65 then '61-65'
        when age >= 66 AND age <= 70 then '66-70'
        when age >= 71 AND age <= 75 then '71-75'
        when age >= 76 AND age <= 80 then '76-80'
        when age > 81  then '>81'
    END as age_group
FROM( 
    SELECT YEAR(current_date()) - CAST(RIGHT(DateBorn,4) AS UNSIGNED)  AS age
    FROM custs
    WHERE  FDID = 'ANGL01'
) as custs2
GROUP BY age_group

您应该检查与预期日期格式不符的值。像这样的查询将为您提供不符合行的示例:

select DateBorn
from custs 
where DateBorn not regexp '^[0-9][0-9][0-9][0-9]$'
and DateBorn not regexp '^[0-3][0-9]\/[0-1][0-9]\/[0-9][0-9][0-9][0-9]$'
limit 25

答案 1 :(得分:0)

假设DateBorn是文本列,请尝试以下操作:

SELECT YEAR(now()) - Year(str_to_date(DateBorn,
    CASE WHEN char_length(DateBorn) = 4
    THEN '01/01/%Y'
    ELSE '%d/%m/%Y'
    END
)) AS age

答案 2 :(得分:0)

MySQL的STR_TO_DATE怎么样?

SELECT STR_TO_DATE(DATE_FORMAT(YourField, '%d/%m/%Y'),'%Y')...

http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_str-to-date

使用此功能可以操纵其他事件。我继承了您无法更改的遗留数据,因此如果您的数据相当一致,此功能将容纳您可以屏蔽的所有内容。

我可能会倒退。如果需要,试试这个。

SELECT date_format(str_to_date(dt3,'%m-%d-%Y'),'%m /%d /%Y')AS my_date FROM dt_tb3

http://www.plus2net.com/sql_tutorial/date-string.php

答案 3 :(得分:0)

current_time()curtime()的别名,返回HH:MM:SS。因此YEAR(current_time())可能会导致一些奇怪的结果。您可能想尝试YEAR(NOW())

您还希望使用STR_TO_DATE(str,format)将varchar解析为日期时间。 (当然,修复架构比修补它更好)确保在表格中更新格式。

SELECT 
    COUNT(*),
    CASE 
        when age < 60 THEN '<60'
        when age >= 61 AND age <= 65 then '61-65'
        when age >= 66 AND age <= 70 then '66-70'
        when age >= 71 AND age <= 75 then '71-75'
        when age >= 76 AND age <= 80 then '76-80'
        when age > 81  then '>81'
    END as age_group

FROM( 
    SELECT YEAR(NOW()) - Year(str_to_date(DateBorn, '%d/%m/%Y')) AS age
    FROM custs
    WHERE  FDID = 'ANGL01'

) as custs2

GROUP BY age_group