【问题标题】:UNION TWO SELECT ON HIVE在 HIVE 上联合两个选择
【发布时间】:2021-07-07 13:15:48
【问题描述】:

我在 HIVE 上有一个类似的数据库。

+--------+------------------+---------+
| rating |    date_upd      | version |
+--------+------------------+---------+
| 3      | 2021-07-01 12:13 | 2.1.9   |
| 5      | 2021-07-01 10:39 | 2.2.6   |
| 4      | 2021-07-02 10:24 | 2.2.7   |
| 5      | 2021-07-02 05:37 | 3.2.4   |
| 1      | 2021-07-02 21:40 | 3.2.5   |

我需要在另一个表中发送两个 SELECT 的结果。如何使用 HiveQL 将这两者合并为一个?

SELECT substr('date_upd',1,10) as 'day',
       count(*) cnt 
FROM tbl_one 
GROUP BY
       substr(date_upd,1,10);


SELECT substr('date_upd',1,7) as 'month',
       count(*) cnt 
FROM table_name 
GROUP BY
      substr('date_upd',1,7);

当我这样做时,它只返回“日”值而不是“月”值。

SELECT 
      substr('date_upd',1,7) as 'month',
      count(*) cnt_month,
      substr('date_upd',1,10) as 'day',
      count(*) cnt_day
FROM table_name 
GROUP BY
      substr('date_upd',1,7),
      substr('date_upd',1,10);

【问题讨论】:

  • 你想要什么结果?只需将union all 放在前两个查询之间即可。
  • 它在运行时返回此错误:` SELECT ... GROUP BY substr('date_upd',1,10) UNION ALL SELECT ... GROUP BY substr('date_upd',1,7 ) ` 编译语句时出错:FAILED: SemanticException 19:5 联合双方的架构应该匹配。 _u1-subquery2 没有字段 day。在令牌“table_name”附近遇到错误

标签: sql hadoop hive bigdata hiveql


【解决方案1】:

这取决于合并对您意味着什么。如果您尝试垂直附加(从标题描述中听起来),您可以试试这个:

垂直追加:

联合:

如果您想在另一份报告之后立即打印一份报告,只需执行 UNION 声明

SELECT substr('date_upd',1,10) as 'day',
       count(*) cnt 
FROM tbl_one 
GROUP BY
       substr(date_upd,1,10);

UNION -- this is the operator you are looking for

SELECT substr('date_upd',1,7) as 'month',
       count(*) cnt 
FROM tbl_one 
GROUP BY
      substr('date_upd',1,7);

水平追加:

加入

但是,如果您尝试水平显示内容,您可能应该使用基于连接的方法(比窗口函数更简单),可能会在月份加入并带来所有 monht_date 和 day_date 列(如果您想实际放置这些列并一个接一个地计数)。

day count_day month count_month
2021-07-01 12:13 2 2021-07 45
2021-07-02 11:07 5 2021-07 45
2021-07-05 07:22 3 2021-07 45

窗口功能:

如果您不想重复列,您可以使用具有分区级别的窗口函数直接在不同级别上聚合。但这显然更先进,可能不是所要求的。只是指路。

你会得到类似的东西:

date count_day count_month
2021-07-01 12:13 2 45
2021-07-02 11:07 5 45
2021-07-05 07:22 3 45

【讨论】:

  • 在这种情况下,它首先执行 SELECT,而不执行第二个并作为不同的查询。
  • 我想带上 HORIZONTAL APPEND,但每当我尝试某些东西时,它都会抱怨 GROUP BY。
猜你喜欢
  • 1970-01-01
  • 2015-08-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多