내장기능


Return Type

Signature

Description

BIGINT

round(double a)

It returns the rounded BIGINT value of the double.

BIGINT

floor(double a)

It returns the maximum BIGINT value that is equal or less than the double.

BIGINT

ceil(double a)

It returns the minimum BIGINT value that is equal or greater than the double.

double

rand(), rand(int seed)

It returns a random number that changes from row to row.

string

concat(string A, string B,...)

It returns the string resulting from concatenating B after A.

string

substr(string A, int start)

It returns the substring of A starting from start position till the end of string A.

string

substr(string A, int start, int length)

It returns the substring of A starting from start position with the given length.

string

upper(string A)

It returns the string resulting from converting all characters of A to upper case.

 

 

 

string

ucase(string A)

Same as above.

string

lower(string A)

It returns the string resulting from converting all characters of B to lower case.

string

lcase(string A)

Same as above.

string

trim(string A)

It returns the string resulting from trimming spaces from both ends of A.

string

ltrim(string A)

It returns the string resulting from trimming spaces from the beginning (left hand side) of A.

string

rtrim(string A)

rtrim(string A) It returns the string resulting from trimming spaces from the end (right hand side) of A.

string

regexp_replace(string A, string B, string C)

It returns the string resulting from replacing all substrings in B that match the Java regular expression syntax with C.

int

size(Map<K.V>)

It returns the number of elements in the map type.

int

size(Array<T>)

It returns the number of elements in the array type.

value of <type>

cast(<expr> as <type>)

It converts the results of the expression expr to <type> e.g. cast('1' as BIGINT) converts the string '1' to it integral representation. A NULL is returned if the conversion does not succeed.

string

from_unixtime(int unixtime)

convert the number of seconds from Unix epoch (1970-01-01 00:00:00 UTC) to a string representing the timestamp of that moment in the current system time zone in the format of "1970-01-01 00:00:00"

string

to_date(string timestamp)

It returns the date part of a timestamp string: to_date("1970-01-01 00:00:00") = "1970-01-01"

int

year(string date)

It returns the year part of a date or a timestamp string: year("1970-01-01 00:00:00") = 1970, year("1970-01-01") = 1970

int

month(string date)

It returns the month part of a date or a timestamp string: month("1970-11-01 00:00:00") = 11, month("1970-11-01") = 11

int

day(string date)

It returns the day part of a date or a timestamp string: day("1970-11-01 00:00:00") = 1, day("1970-11-01") = 1

string

get_json_object(string json_string, string path)

It extracts json object from a json string based on json path specified, and returns json string of the extracted json object. It returns NULL if the input json string is invalid.


 

Example

round() function

hive> SELECT round(2.6)from temp;

3.0

 

floor() function

hive> SELECT floor(2.6)from temp;

2.0

 

ceil() function

hive> SELECT ceil(2.6)from temp;

3.0

 

집계함수

Return Type

Signature

Description

BIGINT

count(*), count(expr),

count(*) - Returns the total number of retrieved rows.

DOUBLE

sum(col), sum(DISTINCT col)

It returns the sum of the elements in the group or the sum of the distinct values of the column in the group.

DOUBLE

avg(col), avg(DISTINCT col)

It returns the average of the elements in the group or the average of the distinct values of the column in the group.

DOUBLE

min(col)

It returns the minimum value of the column in the group.

DOUBLE

max(col)

It returns the maximum value of the column in the group.

 

 

 


'Hadoop ecosystem > Hive' 카테고리의 다른 글

Hive - View / Index  (0) 2017.05.04
Hive - Drop  (0) 2017.05.04
Hive - Create  (0) 2017.05.04
Hive - Data Type  (0) 2017.05.04
Hive / Pig / Spark  (0) 2017.05.04

뷰는 사용자 요구 사항을 기반으로 생성됩니다. 결과 세트 데이터를 뷰로 저장할 수 있습니다. Hive의 뷰 사용은 SQL의 뷰와 동일합니다. 이것은 표준 RDBMS 개념입니다. 뷰에서 모든 DML 작업을 실행할 수 있습니다.

View 만들기

SELECT.을 실행할 때보기를 작성할 수 있습니다. 구문은 다음과 같습니다.

CREATE VIEW [IF NOT EXISTS] view_name [(column_name [COMMENT column_comment], ...)] [COMMENT table_comment] AS SELECT ...


우리가보기에 대한 모범을 보자. Id, Name, Salary, Designation 및 Dept 필드가있는 직원 테이블을 가정합니다. 30000 루타 이상의 급여를받는 직원 세부 정보를 검색하는 쿼리를 생성합니다. 결과를 emp_30000 뷰에 저장합니다 .

+------+--------------+-------------+-------------------+--------+
| ID   | Name         | Salary      | Designation       | Dept   |
+------+--------------+-------------+-------------------+--------+
|1201  | Gopal        | 45000       | Technical manager | TP     |
|1202  | Manisha      | 45000       | Proofreader       | PR     |
|1203  | Masthanvali  | 40000       | Technical writer  | TP     |
|1204  | Krian        | 40000       | Hr Admin          | HR     |
|1205  | Kranthi      | 30000       | Op Admin          | Admin  |
+------+--------------+-------------+-------------------+--------+

다음 쿼리는 위의 시나리오를 사용하여 직원 세부 정보를 검색합니다.

hive> CREATE VIEW emp_30000 AS
SELECT * FROM employee
WHERE salary>30000; 


View 삭제

다음 구문을 사용하여 뷰를 삭제합니다.

DROP VIEW view_name


다음 쿼리는 emp_30000이라는 뷰를 삭제합니다.

hive> DROP VIEW emp_30000;



색인 만들기

인덱스는 테이블의 특정 컬럼에 대한 포인터 일뿐입니다. 인덱스를 만드는 것은 테이블의 특정 열에 포인터를 만드는 것을 의미합니다. 구문은 다음과 같습니다.

CREATE INDEX index_name
ON TABLE base_table_name (col_name, ...)
AS 'index.handler.class.name'
[WITH DEFERRED REBUILD]
[IDXPROPERTIES (property_name=property_value, ...)]
[IN TABLE index_table_name]
[PARTITIONED BY (col_name, ...)]
[
   [ ROW FORMAT ...] STORED AS ...
   | STORED BY ...
]
[LOCATION hdfs_path]
[TBLPROPERTIES (...)]

색인에 대한 예를 들어 봅시다. 이전에 Id, Name, Salary, Designation 및 Dept 필드에 사용했던 것과 동일한 사원 테이블을 사용하십시오. employee 테이블의 salary 열에 index_salary라는 인덱스를 작성하십시오.

다음 쿼리는 인덱스를 만듭니다.

hive> CREATE INDEX inedx_salary ON TABLE employee(salary)
AS 'org.apache.hadoop.hive.ql.index.compact.CompactIndexHandler';

급여 열의 포인터입니다. 열이 수정되면 변경 내용은 인덱스 값을 사용하여 저장됩니다.

색인 삭제

다음 구문은 인덱스를 삭제하는 데 사용됩니다.

DROP INDEX <index_name> ON <table_name>

다음 쿼리는 index_salary라는 인덱스를 삭제합니다.

hive> DROP INDEX index_salary ON employee;




출처 : https://www.tutorialspoint.com/hive/hive_views_and_indexes.htm

'Hadoop ecosystem > Hive' 카테고리의 다른 글

Hive - 내장함수  (0) 2017.05.04
Hive - Drop  (0) 2017.05.04
Hive - Create  (0) 2017.05.04
Hive - Data Type  (0) 2017.05.04
Hive / Pig / Spark  (0) 2017.05.04

데이터베이스를 Hive에 놓는 방법을 설명합니다. SCHEMA와 DATABASE의 사용법은 동일합니다.

데이터베이스 삭제

데이터베이스 삭제는 모든 테이블을 삭제하고 데이터베이스를 삭제하는 명령문입니다. 구문은 다음과 같습니다.

DROP DATABASE StatementDROP (DATABASE|SCHEMA) [IF EXISTS] database_name 
[RESTRICT|CASCADE];


다음 쿼리는 데이터베이스를 삭제하는 데 사용됩니다. 데이터베이스 이름이 userdb 라고 가정합시다 .

hive> DROP DATABASE IF EXISTS userdb;


다음 쿼리는 CASCADE 를 사용하여 데이터베이스를 삭제합니다 . 이는 데이터베이스를 h 제하기 전에 각 테이블을 h 제함을의 L합니다.

hive> DROP DATABASE IF EXISTS userdb CASCADE;


다음 쿼리는 SCHEMA 를 사용하여 데이터베이스를 삭제합니다 .

hive> DROP SCHEMA userdb;


'Hadoop ecosystem > Hive' 카테고리의 다른 글

Hive - 내장함수  (0) 2017.05.04
Hive - View / Index  (0) 2017.05.04
Hive - Create  (0) 2017.05.04
Hive - Data Type  (0) 2017.05.04
Hive / Pig / Spark  (0) 2017.05.04

Hive는 데이터베이스와 테이블을 정의하여 구조화 된 데이터를 분석 할 수있는 데이터베이스 기술입니다구조화 된 데이터 분석의 주제는 데이터를 표 형식으로 저장하고 쿼리를 전달하여 분석하는 것입니다이 장에서는 Hive 데이터베이스를 만드는 방법을 설명합니다. Hive에는 default라는 기본 데이터베이스가 들어 있습니다 .

데이터베이스 문 작성

데이터베이스 생성은 하이브에 데이터베이스를 만드는 데 사용되는 명령문입니다. Hive의 데이터베이스는 네임 스페이스 또는 테이블 모음입니다이 명령문  구문 은 다음과 같습니다.


CREATE DATABASE|SCHEMA [IF NOT EXISTS]<database name>

여기서, NOT NOT EXISTS는 동일한 절이있는 데이터베이스가 이미 있음을 사용자에게 알리는 선택적 절입니다이 명령에서 DATABASE 대신 SCHEMA를 사용할 수 있습니다다음 쿼리를 실행하여 userdb 라는 데이터베이스를 만듭니다 .

hive> CREATE DATABASE [IF NOT EXISTS] userdb;

또는

hive> CREATE SCHEMA userdb;



참조 : https://www.tutorialspoint.com/hive/hive_create_database.htm

'Hadoop ecosystem > Hive' 카테고리의 다른 글

Hive - View / Index  (0) 2017.05.04
Hive - Drop  (0) 2017.05.04
Hive - Data Type  (0) 2017.05.04
Hive / Pig / Spark  (0) 2017.05.04
Hive - JOIN  (0) 2017.05.04

하이브의 모든 데이터 타입은 아래와 같이 4가지로 분류된다.

Column Types

Literals

Null Values

Complex Types

 

Column Types

Integral Types

String Types

Integral Types

Timestamp

Union Types

 

Integer typeINT로 표기하고, INT보다 작은 타입은 SMALLINT, 그보다 작은건 TINYINT로 표기한다. 그리고 INT보다 큰 타입은 BIGINT라 표기한다.


Type

Postfix

Example

TINYINT

Y

10Y

SMALLINT

S

10S

INT

-

10

BIGINT

L

10L

 

String Types

String typesingle quotes (' ') 또는 double quotes (" ")로 표기할 수 있다. 그리고 VARCHARCHAR가 있고, C유형 이스케이프 유형을 따른다.


Data Type

Length

VARCHAR

1 to 65355

CHAR

255

 

Timestamp

It supports traditional UNIX timestamp with optional nanosecond precision. It supports java.sql.Timestamp format “YYYY-MM-DD HH:MM:SS.fffffffff” and format “yyyy-mm-dd hh:mm:ss.ffffffffff”.

Dates

DATA값은 year/month/day format으로 되어있다.

{{YYYY-MM-DD}}.

 

Union Types

Union은 이기종 데이터 유형의 모음입니다create union 사용하여 인스턴스를 만들 수 있습니다 . 구문과 예제는 다음과 같습니다.

 

UNIONTYPE<int,double, array<string>,struct<a:int,b:string>>

 

{0:1}

{1:2.0}

{2:["three","four"]}

{3:{"a":5,"b":"five"}}

{2:["six","seven"]}

{3:{"a":8,"b":"eight"}}

{0:9}

{1:10.0}

 

Literal

하이브에는 다음과 같은 리터럴이 사용됩니다.

 

부동 소수점

부동 소수점 유형은 소수점이있는 숫자입니다일반적으로이 유형의 데이터는 DOUBLE 데이터 유형으로 구성됩니다.

 

십진수

십진 형식 데이터는 DOUBLE 데이터 형식보다 높은 범위의 부동 소수점 값입니다십진 형식의 범위는 약 -10 -308 ~ 10 308 입니다.

 

Null Value

Missing values are represented by the special value NULL.

 

Complex Types

The Hive complex data types are as follows:

 

Arrays

JAVA의 배열과 비슷하다.

Syntax: ARRAY<data_type>

 

Maps

JAVAMAPS와 비슷하다.

Syntax: MAP<primitive_type, data_type>

 

Structs

Hive의 구조체는 주석이있는 복합 데이터를 사용하는 것과 유사하다.

Syntax: STRUCT<col_name : data_type [COMMENT col_comment],...>

'Hadoop ecosystem > Hive' 카테고리의 다른 글

Hive - Drop  (0) 2017.05.04
Hive - Create  (0) 2017.05.04
Hive / Pig / Spark  (0) 2017.05.04
Hive - JOIN  (0) 2017.05.04
Hive - SELECT(WHERE / ORDER BY / GROUP BY)  (0) 2017.05.04

Hive

매우 SQL과 비슷한 HQL(Hive Query Language)이라는 언어를 사용합니다. 프로그래머가 아닌 사용자에게 Hadoop의 데이터를 쿼리하고 분석 할 수 있는 기능을 제공합니다. 기본적으로 Map-ReduceTez위에 추상 레이어가 있습니다.

 

Pig

- Pig Latin이라는 스크립팅 언어를 사용합니다. 전문 Java 프로그래머 일 필요는 없지만 코딩 기술이 필요합니다. 또한 map-reduce Tez 위에 추상 레이어가 있습니다.

 

- 고도로 구조화되지 않은 데이터를 가져 와서 의미있는 형식으로 변환하는 데 사용되는 도구입니까? 예를들어. 임의로 생성 된 로그를 가져 와서 각 필드가 의미하는 쉼표로 구분 된 형식으로 변환합니다. Pig 스크립트는 데이터 집합에서 Map Reduce 작업을 실행하고 다른 데이터 집합으로 변환합니다.

 

- Pig는 스크립팅 언어이기 때문에 복잡한 알고리즘을 매우 효율적으로 작성할 수 있습니다. 예를 들어 Hadoop의 고전적인 단어 계산 예제는 Java Map-Reduce 프로그램에서 100 줄의 코드를 사용하지만 Pig에서는 2-3 줄만 필요합니다. Java에서 Map-Reduce를 작성하는 것보다 복잡한 데이터 처리 알고리즘을 빠르게 작성하기 위한 대안으로 Pig를 고려하십시오. 또한 PigETL 특정 처리에 광범위하게 사용됩니다.

 

- 구조화되지 않은 데이터 -> Pig(합리적인 데이터로 변환) -> 하이브(SQL을 실행하고 결합하여 원하는 통계를 제공)

 

Spark

in-memory computing에 중점을 두어 Hadoopmap-reduce의 후속 제품입니다. Spark를 사용하려면 자바를 잘알아야 합니다. 비교적 견고한 새로운 프로젝트 인 Spark SQL도 있습니다.

 

 

프로그래밍 패러다임을 줄입니다. RDD(Resilient Distributed DataSet아키텍처에서 작동하며 기존 Map Reduce에 비해 10-100% 빨라졌습니다. 그래서 요즘은 Spark에서 BIG Data 인프라를 구축하기 시작했습니다

 

Hadoop에서 어떤 것을 선택해서 분석해야하는가?

1. 데이터를 분석하려는 사람이 얼마나 기술적인가

그 사람이 SQL을 알고 그것에 관한 것이라면 Hive가 확실한 선택입니다.

 

2. 얼마나 빨리 처리해야하는가

Hive Pig는 배치 지향 프레임 워크를 사용하므로 분석 작업이 수분 또는 몇 시간 동안 실행됩니다. 스파크는 빠르지 만 훨씬 낮은 레벨입니다.

 

3. 데이터가 얼마나 잘 구조화(Structured Data)되었는가.

CSV 파일과 같은 것을 사용하고 있습니까? 아니면 지저분한 웹 로그일까요? 잘 구조화되어 있다면 분석 할 데이터를 하이브 테이블에 로드하고 진행하는 데 걸리는 시간을 훨씬 단축 할 수 있습니다. 데이터 분석과 구문 분석이 많은 경우 Pig와 스파크를 고려해야합니다.







참조 : https://www.quora.com/What-is-the-criteria-to-chose-Pig-Hive-Hbase-Storm-Solr-or-Spark-to-analyze-your-data-in-Hadoop

'Hadoop ecosystem > Hive' 카테고리의 다른 글

Hive - Drop  (0) 2017.05.04
Hive - Create  (0) 2017.05.04
Hive - Data Type  (0) 2017.05.04
Hive - JOIN  (0) 2017.05.04
Hive - SELECT(WHERE / ORDER BY / GROUP BY)  (0) 2017.05.04

JOIN is a clause that is used for combining specific fields from two tables by using values common to each one. It is used to combine records from two or more tables in the database. It is more or less similar to SQL JOIN.

Syntax

join_table: table_reference JOIN table_factor [join_condition] | table_reference {LEFT|RIGHT|FULL} [OUTER] JOIN table_reference join_condition | table_reference LEFT SEMI JOIN table_reference join_condition | table_reference CROSS JOIN table_reference [join_condition]


Example

We will use the following two tables in this chapter. Consider the following table named CUSTOMERS..

+----+----------+-----+-----------+----------+ 
| ID | NAME     | AGE | ADDRESS   | SALARY   | 
+----+----------+-----+-----------+----------+ 
| 1  | Ramesh   | 32  | Ahmedabad | 2000.00  |  
| 2  | Khilan   | 25  | Delhi     | 1500.00  |  
| 3  | kaushik  | 23  | Kota      | 2000.00  | 
| 4  | Chaitali | 25  | Mumbai    | 6500.00  | 
| 5  | Hardik   | 27  | Bhopal    | 8500.00  | 
| 6  | Komal    | 22  | MP        | 4500.00  | 
| 7  | Muffy    | 24  | Indore    | 10000.00 | 
+----+----------+-----+-----------+----------+


Consider another table ORDERS as follows:

+-----+---------------------+-------------+--------+ 
|OID  | DATE                | CUSTOMER_ID | AMOUNT | 
+-----+---------------------+-------------+--------+ 
| 102 | 2009-10-08 00:00:00 |           3 | 3000   | 
| 100 | 2009-10-08 00:00:00 |           3 | 1500   | 
| 101 | 2009-11-20 00:00:00 |           2 | 1560   | 
| 103 | 2008-05-20 00:00:00 |           4 | 2060   | 
+-----+---------------------+-------------+--------+


There are different types of joins given as follows:

  • JOIN
  • LEFT OUTER JOIN
  • RIGHT OUTER JOIN
  • FULL OUTER JOIN

JOIN(INNER JOIN)

JOIN clause is used to combine and retrieve the records from multiple tables. JOIN is same as OUTER JOIN in SQL. A JOIN condition is to be raised using the primary keys and foreign keys of the tables.

The following query executes JOIN on the CUSTOMER and ORDER tables, and retrieves the records:

hive> SELECT c.ID, c.NAME, c.AGE, o.AMOUNT FROM CUSTOMERS c

JOIN ORDERS o ON (c.ID = o.CUSTOMER_ID);


On successful execution of the query, you get to see the following response:

+----+----------+-----+--------+ 
| ID | NAME     | AGE | AMOUNT | 
+----+----------+-----+--------+ 
| 3  | kaushik  | 23  | 3000   | 
| 3  | kaushik  | 23  | 1500   | 
| 2  | Khilan   | 25  | 1560   | 
| 4  | Chaitali | 25  | 2060   | 
+----+----------+-----+--------+


LEFT OUTER JOIN

The HiveQL LEFT OUTER JOIN returns all the rows from the left table, even if there are no matches in the right table. This means, if the ON clause matches 0 (zero) records in the right table, the JOIN still returns a row in the result, but with NULL in each column from the right table.

A LEFT JOIN returns all the values from the left table, plus the matched values from the right table, or NULL in case of no matching JOIN predicate.


The following query demonstrates LEFT OUTER JOIN between CUSTOMER and ORDER tables:

hive> SELECT c.ID, c.NAME, o.AMOUNT, o.DATE 
FROM CUSTOMERS c 
LEFT OUTER JOIN ORDERS o 
ON (c.ID = o.CUSTOMER_ID);


On successful execution of the query, you get to see the following response:

+----+----------+--------+---------------------+ 
| ID | NAME     | AMOUNT | DATE                | 
+----+----------+--------+---------------------+ 
| 1  | Ramesh   | NULL   | NULL                | 
| 2  | Khilan   | 1560   | 2009-11-20 00:00:00 | 
| 3  | kaushik  | 3000   | 2009-10-08 00:00:00 | 
| 3  | kaushik  | 1500   | 2009-10-08 00:00:00 | 
| 4  | Chaitali | 2060   | 2008-05-20 00:00:00 | 
| 5  | Hardik   | NULL   | NULL                | 
| 6  | Komal    | NULL   | NULL                | 
| 7  | Muffy    | NULL   | NULL                | 
+----+----------+--------+---------------------+


RIGHT OUTER JOIN

The HiveQL RIGHT OUTER JOIN returns all the rows from the right table, even if there are no matches in the left table. If the ON clause matches 0 (zero) records in the left table, the JOIN still returns a row in the result, but with NULL in each column from the left table.

A RIGHT JOIN returns all the values from the right table, plus the matched values from the left table, or NULL in case of no matching join predicate.

The following query demonstrates RIGHT OUTER JOIN between the CUSTOMER and ORDER tables.

hive> SELECT c.ID, c.NAME, o.AMOUNT, o.DATE

FROM CUSTOMERS c

RIGHT OUTER JOIN ORDERS o

ON (c.ID = o.CUSTOMER_ID);


On successful execution of the query, you get to see the following response:

+------+----------+--------+---------------------+ 
| ID   | NAME     | AMOUNT | DATE                | 
+------+----------+--------+---------------------+ 
| 3    | kaushik  | 3000   | 2009-10-08 00:00:00 | 
| 3    | kaushik  | 1500   | 2009-10-08 00:00:00 | 
| 2    | Khilan   | 1560   | 2009-11-20 00:00:00 | 
| 4    | Chaitali | 2060   | 2008-05-20 00:00:00 | 
+------+----------+--------+---------------------+


FULL OUTER JOIN

The HiveQL FULL OUTER JOIN combines the records of both the left and the right outer tables that fulfil the JOIN condition. The joined table contains either all the records from both the tables, or fills in NULL values for missing matches on either side.

The following query demonstrates FULL OUTER JOIN between CUSTOMER and ORDER tables:

hive> SELECT c.ID, c.NAME, o.AMOUNT, o.DATE 
FROM CUSTOMERS c 
FULL OUTER JOIN ORDERS o 
ON (c.ID = o.CUSTOMER_ID);


On successful execution of the query, you get to see the following response:

+------+----------+--------+---------------------+ 
| ID   | NAME     | AMOUNT | DATE                | 
+------+----------+--------+---------------------+ 
| 1    | Ramesh   | NULL   | NULL                | 
| 2    | Khilan   | 1560   | 2009-11-20 00:00:00 | 
| 3    | kaushik  | 3000   | 2009-10-08 00:00:00 | 
| 3    | kaushik  | 1500   | 2009-10-08 00:00:00 | 
| 4    | Chaitali | 2060   | 2008-05-20 00:00:00 | 
| 5    | Hardik   | NULL   | NULL                | 
| 6    | Komal    | NULL   | NULL                |
| 7    | Muffy    | NULL   | NULL                |  
| 3    | kaushik  | 3000   | 2009-10-08 00:00:00 | 
| 3    | kaushik  | 1500   | 2009-10-08 00:00:00 | 
| 2    | Khilan   | 1560   | 2009-11-20 00:00:00 | 
| 4    | Chaitali | 2060   | 2008-05-20 00:00:00 | 
+------+----------+--------+---------------------+


참조 : https://www.tutorialspoint.com/hive/hiveql_joins.htm

'Hadoop ecosystem > Hive' 카테고리의 다른 글

Hive - Drop  (0) 2017.05.04
Hive - Create  (0) 2017.05.04
Hive - Data Type  (0) 2017.05.04
Hive / Pig / Spark  (0) 2017.05.04
Hive - SELECT(WHERE / ORDER BY / GROUP BY)  (0) 2017.05.04

Syntax

SELECT 구문은 다음과 같은 Syntax를 가진다.

SELECT [ALL | DISTINCT] select_expr, select_expr, ... 
FROM table_reference 
[WHERE where_condition] 
[GROUP BY col_list] 
[HAVING having_condition] 
[CLUSTER BY col_list | [DISTRIBUTE BY col_list] [SORT BY col_list]] 
[LIMIT number];


Example - WHERE

Let us take an example for SELECT…WHERE clause. Assume we have the employee table as given below, with fields named Id, Name, Salary, Designation, and Dept. Generate a query to retrieve the employee details who earn a salary of more than Rs 30000.

+------+--------------+-------------+-------------------+--------+
| ID   | Name         | Salary      | Designation       | Dept   |
+------+--------------+-------------+-------------------+--------+
|1201  | Gopal        | 45000       | Technical manager | TP     |
|1202  | Manisha      | 45000       | Proofreader       | PR     |
|1203  | Masthanvali  | 40000       | Technical writer  | TP     |
|1204  | Krian        | 40000       | Hr Admin          | HR     |
|1205  | Kranthi      | 30000       | Op Admin          | Admin  | 
+------+--------------+-------------+-------------------+--------+

The following query retrieves the employee details using the above scenario:

hive> SELECT * FROM employee WHERE salary>30000;

On successful execution of the query, you get to see the following response:

+------+--------------+-------------+-------------------+--------+
| ID   | Name         | Salary      | Designation       | Dept   |
+------+--------------+-------------+-------------------+--------+
|1201  | Gopal        | 45000       | Technical manager | TP     |
|1202  | Manisha      | 45000       | Proofreader       | PR     |
|1203  | Masthanvali  | 40000       | Technical writer  | TP     |
|1204  | Krian        | 40000       | Hr Admin          | HR     |
+------+--------------+-------------+-------------------+--------+



Example - ORDER BY

Let us take an example for SELECT...ORDER BY clause. Assume employee table as given below, with the fields named Id, Name, Salary, Designation, and Dept. Generate a query to retrieve the employee details in order by using Department name.

+------+--------------+-------------+-------------------+--------+
| ID   | Name         | Salary      | Designation       | Dept   |
+------+--------------+-------------+-------------------+--------+
|1201  | Gopal        | 45000       | Technical manager | TP     |
|1202  | Manisha      | 45000       | Proofreader       | PR     |
|1203  | Masthanvali  | 40000       | Technical writer  | TP     |
|1204  | Krian        | 40000       | Hr Admin          | HR     |
|1205  | Kranthi      | 30000       | Op Admin          | Admin  |
+------+--------------+-------------+-------------------+--------+

The following query retrieves the employee details using the above scenario:

hive> SELECT Id, Name, Dept FROM employee ORDER BY DEPT;

On successful execution of the query, you get to see the following response:

+------+--------------+-------------+-------------------+--------+
| ID   | Name         | Salary      | Designation       | Dept   |
+------+--------------+-------------+-------------------+--------+
|1205  | Kranthi      | 30000       | Op Admin          | Admin  |
|1204  | Krian        | 40000       | Hr Admin          | HR     |
|1202  | Manisha      | 45000       | Proofreader       | PR     |
|1201  | Gopal        | 45000       | Technical manager | TP     |
|1203  | Masthanvali  | 40000       | Technical writer  | TP     |
+------+--------------+-------------+-------------------+--------+



Example - GROUP BY

Let us take an example of SELECT…GROUP BY clause. Assume employee table as given below, with Id, Name, Salary, Designation, and Dept fields. Generate a query to retrieve the number of employees in each department.

+------+--------------+-------------+-------------------+--------+ 
| ID   | Name         | Salary      | Designation       | Dept   |
+------+--------------+-------------+-------------------+--------+ 
|1201  | Gopal        | 45000       | Technical manager | TP     | 
|1202  | Manisha      | 45000       | Proofreader       | PR     | 
|1203  | Masthanvali  | 40000       | Technical writer  | TP     | 
|1204  | Krian        | 45000       | Proofreader       | PR     | 
|1205  | Kranthi      | 30000       | Op Admin          | Admin  |
+------+--------------+-------------+-------------------+--------+

The following query retrieves the employee details using the above scenario.

hive> SELECT Dept,count(*) FROM employee GROUP BY DEPT;

On successful execution of the query, you get to see the following response:

+------+--------------+ 
| Dept | Count(*)     | 
+------+--------------+ 
|Admin |    1         | 
|PR    |    2         | 
|TP    |    3         | 
+------+--------------+


참조 : https://www.tutorialspoint.com/hive/hiveql_select_where.htm


'Hadoop ecosystem > Hive' 카테고리의 다른 글

Hive - Drop  (0) 2017.05.04
Hive - Create  (0) 2017.05.04
Hive - Data Type  (0) 2017.05.04
Hive / Pig / Spark  (0) 2017.05.04
Hive - JOIN  (0) 2017.05.04

+ Recent posts