首页 > 解决方案 > Presto SQL-将字符串数据类型中的日期转换为日期格式yyyy/mm/dd

问题描述

ds:yyyy/mm/dd 格式的日期。它以文本的形式存储,我们使用presto来运行。不需要日期功能

CREATE TABLE job_data(
    ds DATE,
    job_id INT NOT NULL,
    actor_id INT NOT NULL,
    event VARCHAR(15) NOT NULL,
    language VARCHAR(15) NOT NULL,
    time_spent INT NOT NULL,
    org CHAR(2) );

INSERT INTO job_data (ds, job_id, actor_id, event, language, time_spent, org)
VALUES ('2020-11-30', 21, 1001, 'skip', 'English', 15, 'A'),
    ('2020-11-30', 22, 1006, 'transfer', 'Arabic', 25, 'B'),
    ('2020-11-29', 23, 1003, 'decision', 'Persian', 20, 'C'),
    ('2020-11-28', 23, 1005,'transfer', 'Persian', 22, 'D'),
    ('2020-11-28', 25, 1002, 'decision', 'Hindi', 11, 'B'),
    ('2020-11-27', 11, 1007, 'decision', 'French', 104, 'D'),
    ('2020-11-26', 23, 1004, 'skip', 'Persian', 56, 'A'),
    ('2020-11-25', 20, 1003, 'transfer', 'Italian', 45, 'C');

在这里,我使用ds作为日期数据类型。

我的代码:

select ds, count(job_id) as jobs_per_day, sum(time_spent)/3600 as hours_spent 
from job_data  
where ds >='2020-11-01'  and ds <='2020-11-30'  
group by ds ;

这就是我所做的,但我必须在字符串中输入日期,我不明白如何在不使用任何函数的情况下将其转换为日期。我正在使用 mysql 工作台 8.0。

标签: mysqlmysql-workbenchpresto

解决方案


没有函数就不能将字符串转换为日期。在 Presto 中,您可以使用date_parse. 尝试:

select cast(date_parse(ds,'%Y-%m-%d') as date) as the_date , 
count(job_id) as jobs_per_day, 
sum(time_spent)/3600 as hours_spent 
from job_data  
where the_date >='2020-11-01'  and the_date <='2020-11-30'  
group by the_date ;

推荐阅读