sql—如何在where子句中对select语句中包含count/distinct/case/when的列进行筛选

ldxq2e6h  于 2021-05-29  发布在  Hadoop
关注(0)|答案(1)|浏览(441)

在hadoop上使用sql。
我有一个ID列表,其中我试图计算2种不同的客人评论数据点的总数。为了 guest_review_1 我已经把总数退了。为了 guest_review_2 我把总数分成5个区间。
我正在努力的是在的where子句中设置一个过滤器 guest_review_1 我不包括总数小于5的属性。
有解决办法吗?嵌套的select语句?
包括以下查询示例:

Select 
id,
count(distinct guest_review_1) as "Guest_Reviews",
count(distinct(case when guest_review_2 < 1 then guest_review_1 end)) as Group1,
Count(distinct(case when guest_review_2 >=2 AND guest_review_2 <3 then guest_review_1 end)) as Group2,
From  table_name
Where
guest_review_2 IS NOT NULL
AND guest_review_1 >=5
AND date BETWEEN '2017-01-01' AND '2017-01-31'
Group By id
ds97pgxw

ds97pgxw1#

我不能完全肯定这个词的意思 group_1 以及 group_2 示例查询中的聚合。然而,问题的实质似乎是如何基于聚合函数的结果过滤结果集( count )而不是过滤单个输入行的值。apachehive通过使用sql HAVING 条款。
在下面的示例中,输入关系包含6行 id 设置为 1 和4排 id 设置为 2 . 查询包含子句 HAVING guest_reviews >= 5 . 因为 HAVING 子句中,结果集只包含 id1 . 没有带的输出行 id 设置为 2 .

WITH table_name AS (
    SELECT 1 AS id, 1 AS guest_review_1, 1 AS guest_review_2 UNION ALL
    SELECT 1 AS id, 2 AS guest_review_1, 2 AS guest_review_2 UNION ALL
    SELECT 1 AS id, 3 AS guest_review_1, 3 AS guest_review_2 UNION ALL
    SELECT 1 AS id, 4 AS guest_review_1, 4 AS guest_review_2 UNION ALL
    SELECT 1 AS id, 5 AS guest_review_1, 5 AS guest_review_2 UNION ALL
    SELECT 1 AS id, 6 AS guest_review_1, 6 AS guest_review_2 UNION ALL
    SELECT 2 AS id, 1 AS guest_review_1, 1 AS guest_review_2 UNION ALL
    SELECT 2 AS id, 2 AS guest_review_1, 2 AS guest_review_2 UNION ALL
    SELECT 2 AS id, 3 AS guest_review_1, 3 AS guest_review_2 UNION ALL
    SELECT 2 AS id, 4 AS guest_review_1, 4 AS guest_review_2
)
SELECT
    id,
    count(DISTINCT guest_review_1) AS guest_reviews,
    count(DISTINCT(CASE WHEN guest_review_2 < 1 THEN guest_review_1 END)) AS group_1,
    count(DISTINCT(CASE WHEN guest_review_2 >= 2 AND guest_review_2 < 3 THEN guest_review_1 END)) as group_2
FROM table_name
WHERE guest_review_2 IS NOT NULL
GROUP BY id
HAVING guest_reviews >= 5
;

相关问题