hive SQL SELECT,其中包含具有多个值的额外列

kokeuurv  于 2022-11-29  发布在  Hive
关注(0)|答案(1)|浏览(199)

我有一个包含column_1、column_2、column_3的表,并通过以下方法选择该表:

SELECT
    column_1,
    column_2,
    column_3
From 
    table

我想要添加一个额外的列“hour”,它将具有从0到23的24个可能值。结果是每行[column_1,column_2,column_3]重复24次,其中包含额外列hour的所有可能的24个值:

column_1, column_2, column_3, hour
   'aaa',     'bbb',    'ccc',    0
   'aaa',     'bbb',    'ccc',    1
   ...

我该怎么做?

tgabmvqs

tgabmvqs1#

您可以创建一个包含所需小时值的临时表或视图。然后,您可以连接新的小时视图或表以重复结果。以下是我的代码片段,我刚刚修改了that answer

CREATE VIEW TEST.HOURS
AS SELECT 0 n UNION ALL SELECT 1  UNION ALL SELECT 2  UNION ALL 
   SELECT 3   UNION ALL SELECT 4  UNION ALL SELECT 5  UNION ALL
   SELECT 6   UNION ALL SELECT 7  UNION ALL SELECT 8  UNION ALL
   SELECT 9   UNION ALL SELECT 10 UNION ALL SELECT 11 UNION ALL
   SELECT 12  UNION ALL SELECT 13 UNION ALL SELECT 14 UNION ALL 
   SELECT 15  UNION ALL SELECT 16 UNION ALL SELECT 17 UNION ALL 
   SELECT 18  UNION ALL SELECT 19 UNION ALL SELECT 20 UNION ALL 
   SELECT 21  UNION ALL SELECT 22 UNION ALL SELECT 23;

GO

SELECT t.column1, t.column2, t.column3, i.n as hour
FROM yourTable t
JOIN TEST.HOURS i 
ON i.n between 0 and 23
order by t.column1, t.column2, t.column3, i.n

相关问题