将数据从一张表加载到 hive 中的另一张表

时间:2020-12-21 10:21:32

标签: pyspark hive apache-spark-sql hiveql create-table

我在 hive 中有一个名为 a.table1 的表,其中包含 id、name、class 列,并且它已满载数据。

id name class 
1   a     1
11  b     14

我想从 a.table1 创建一个新表 b.table2,其中包含字段 id、name、class、status。 当 id 小于 10 时,类和状态将具有相同的值,否则值为 0。

id name class status
1   a     1     1
11  b     14    0

我正在做的是,创建一个表:

CREATE TABLE IF NOT EXISTS b.table2(
id BIGINT,
name string,
class int,
status int
)

如何加载表格的内容?或者有什么更好的方法吗?


spark = SparkSession.builder.enableHiveSupport().getOrCreate()
sc = spark.sparkContext
sqlContext = spark._wrapped


2 个答案:

答案 0 :(得分:1)

只需做一个选择并将结果插入到表 2 中:

insert into b.table2 (
    select *, case when id < 10 then class else 0 end as status from a.table1
);

答案 1 :(得分:1)

CTAS 将在单个语句中创建和加载表:

CREATE TABLE table2 AS
 select id, name, class, status 
   from table1;