[英]How to insert dates from a csv file which are in multiple formats into a column(whose data type is date i.e 'yyyy-mm-dd' ) of hive table
I'm trying to insert data from a csv file into a hive table where date in csv files are in formats like 'mm/dd/yyyy','mm-dd-yyyy' which i have to insert in a hive table in a column whose data-type is date ie 'yyyy-mm-dd'. 我正在尝试将csv文件中的数据插入到hive表中,其中csv文件中的日期格式为'mm / dd / yyyy','mm-dd-yyyy',我必须将其插入到Hive表中数据类型为日期的列,即“ yyyy-mm-dd”。
Firstly i tried to load data from csv file inside a table whose date is stored with data-type as string. 首先,我尝试从表中的csv文件加载数据,该表的日期以数据类型存储为字符串。 Then, i tried to insert the same data into a new table whose data-type is date but i was only able to load dates inside table of one format while other format stored as NULL. 然后,我试图将相同的数据插入到数据类型为date的新表中,但是我只能在一种格式的表中加载日期,而其他格式存储为NULL。
create table sample1(order_id int, order_dt string);
load data local inpath "\home\cloudera\data.txt" into table sample1;
create table sample2(order_id int, order_dt date);
insert into table sample2 select order_id,
to_date(from_unixtime(unix_timestamp(order_dt,'mm/dd/yyyy'),'yyyy-mm-dd'))
from sample1;
csv file: CSV文件:
order_id order_date order_id order_date
1 10/27/2016 1 10/27/2016
2 10/27/2018 2 10/27/2018
3 11/23/2016 3 11/23/2016
4 09-23-2013 4 2013年9月23日
5 08-20-2010 5 08-20-2010
6 05-13-2017 6 05-13-2017
7 02/15/2009 7 02/15/2009
output after: 输出后:
select * from sample2; 从sample2中选择*;
1 2016-10-27 1 2016年10月27日
2 2018-10-27 2 2018-10-27
3 2016-11-23 3 2016-11-23
4 NULL 4 NULL
5 NULL 5空
6 NULL 6 NULL
7 2009-02-15 7 2009-02-15
Here, I'm getting NULL for other date format. 在这里,对于其他日期格式,我将得到NULL。
You can use COALESCE
function here. 您可以在此处使用COALESCE
函数。 if first to_date
function returns null then it will execute the 2nd argument, you can pass any number of patterns this way. 如果第一个to_date
函数返回null,则它将执行第二个参数,您可以通过这种方式传递任意数量的模式。
insert into table sample2
select
order_id,
COALESCE(to_date(from_unixtime(unix_timestamp(order_dt,'mm/dd/yyyy'),'yyyy-mm-dd')),to_date(from_unixtime(unix_timestamp(order_dt,'mm-dd-yyyy'),'yyyy-mm-dd')))
from sample1;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.