【问题标题】:Hive - select data from group with at least one row containingHive - 从组中选择至少一行包含的数据
【发布时间】:2017-07-06 22:52:50
【问题描述】:

假设我在蜂巢中有一张这样的桌子:

|Id|Data |Data2 |Groupkey|
|1 |One  |      |Group1  |
|2 |Two  |Stuff |Group1  |
|3 |Shoes|Some  |Group2  |
|4 |four |Stuff |Group2  |
|5 |Three|Notme |Group3  |

对于在Data2 中包含“Stuff”的每个组,我想从除Stuff 之外的行中获取具有Groupkey 和Data 的行,并从“Stuff”行中获取Data2。

所以结果数据集看起来像

|Group |Data |Data2|
|Group1|One  |Two  |
|Group2|Shoes|four |

我希望用GROUP BY 来做点什么,我开始用了

SELECT Data, Groupkey FROM (SELECT Data, GroupKey FROM MyTable GROUP BY Groupkey) WHERE Data2 <> 'Stuff' 但这失败了,这表明我需要在分组依据中包含数据,但这不是我想要分组的依据?

而且我不确定如何只选择包含一行具有某些数据的组。

【问题讨论】:

    标签: sql hive hiveql


    【解决方案1】:
    select      Groupkey                                            as `Group`
               ,min (case when Data2 <> 'Stuff' then Data end)      as Data
               ,min (case when Data2 =  'Stuff' then Data end)      as Data2
    
    from        MyTable
    
    group by    Groupkey
    
    having      count (case when Data2 = 'Stuff' then 1 end) > 0
    ;
    

    +--------+-------+-------+
    | group  | data  | data2 |
    +--------+-------+-------+
    | Group1 | One   | Two   |
    | Group2 | Shoes | four  |
    +--------+-------+-------+
    

    【讨论】:

      【解决方案2】:
      SELECT DISTINCT Groupkey, t1.Data, t2.Data as Data2 
      FROM t t1
      INNER JOIN t t2
      ON t1.Groupkey = t2.Groupkey
      AND t1.Data2 <> t2.Data2
      WHERE t2.Data2 = 'Stuff'
      

      【讨论】:

        猜你喜欢
        • 2022-01-27
        • 2020-04-05
        • 2021-10-05
        • 1970-01-01
        • 2018-02-13
        • 1970-01-01
        • 2017-07-14
        • 2019-03-17
        • 1970-01-01
        相关资源
        最近更新 更多