복붙노트

[HADOOP] 집계를 사용하여 Hive에서 데이터를 피벗하는 방법

HADOOP

집계를 사용하여 Hive에서 데이터를 피벗하는 방법

아래와 같은 테이블 데이터가 있으며 집계로 데이터를 피벗하고 싶습니다.

ColumnA    ColumnB            ColumnC
1          complete            Yes
1          complete            Yes
2          In progress         No
2          In progress         No 
3          Not yet started     initiate 
3          Not yet started     initiate 

아래처럼 피벗하고 싶습니다

ColumnA          Complete    In progress     Not yet started
1                 2               0                0
2                 0               2                0
3                 0               0                2

어쨌든 우리는 하이브 또는 임팔라에서 이것을 달성 할 수 있습니까?

해결법

  1. ==============================

    1.합계 집계 사용 사례 :

    합계 집계 사용 사례 :

    select ColumnA,    
           sum(case when ColumnB='complete'        then 1 else 0 end) as Complete,
           sum(case when ColumnB='In progress'     then 1 else 0 end) as In_progress,
           sum(case when ColumnB='Not yet started' then 1 else 0 end) as Not_yet_started
      from table
     group by ColumnA
     order by ColumnA --remove if order is not necessary
    ;
    
  2. ==============================

    2.이것이 스파크 스칼라에서 이것을 할 수있는 방법입니다.

    이것이 스파크 스칼라에서 이것을 할 수있는 방법입니다.

         val conf = spark.sparkContext.hadoopConfiguration
            val test = spark.sparkContext.parallelize(List(  ("1", "Complete", "yes"),
                                            ("1", "Complete", "yes"),
                                            ("2", "Inprogress", "no"),
                                            ("2", "Inprogress", "no"),
                                           ("3", "Not yet started", "initiate"),
                                            ("3", "Not yet started", "initiate"))
    
    
                                            ).toDF("ColumnA","ColumnB","ColumnC")
          test.show()
           val test_pivot = test.groupBy("ColumnA")
                               .pivot("ColumnB")
                               .agg(count("columnC"))
    
      test_pivot.na.fill(0)show(false)
    
    
           }
    

    그리고 출력

    |ColumnA|Complete|Inprogress|Not yet started|
    +-------+--------+----------+---------------+
    |3      |0       |0         |2              |
    |1      |2       |0         |0              |
    |2      |0       |2         |0              |
    +-------+--------+----------+---------------+
    
  3. from https://stackoverflow.com/questions/52191603/how-to-pivot-data-in-hive-with-aggregation by cc-by-sa and MIT license